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

懵懂的女人 提交于 2019-12-01 21:42:01

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!