How to set Regex Expression as the Mask for a MaskedTextBox in C#?

Mobin picture Mobin · Jun 19, 2010 · Viewed 10.3k times · Source

I want to set the Mask of MaskedtextBox from Regex expression. Such as i want a valid email, Decimal values and other regex expressions against a MaskedtextBox.

Answer

Reinderien picture Reinderien · Jun 19, 2010

For reference, this describes what you can do with a mask: http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask(VS.90).aspx

The only time I could see you needing to set the mask from a regular expression is if you don't have control over the regular expression, for example if it's acquired from the user or from a database. Masks are in a different format than regular expressions and aren't as powerful. So some of the time, it might not even be able to be done. As far as I know, you simply can't do validation of something like an email with a mask, because the position and length of the various parts changes.

Instead of using a mask, you should probably just use regular validation, and then you can use the regular expressions directly. Make sure that the CausesValidation property of the (regular, not masked) textbox is true, then intercept the Validating event and if the regular expression doesn't match, set the CancelEventArgs.Cancel to true.