Tuesday, February 19, 2008

Regular Expression Negation for Required Field Validators

Out of the box ASP.NET regular expression validators have the following behavior:

Does control value match regular expression? If yes validation passes, else validation fails.

But what if you wanted the following:

Does control value NOT match regular expression? If yes validation passes, else validation fails.

Turns out there is no "If expression not match" property on a regular expression validator. Now, you can make your own custom regular expression control, or you can buy a toolset. But it turns out you might be able to do it in your regular expression itself.

This can be accomplished by using something called a Negative lookahead assertion. It succeeds if the contained expression doesn't match at the current position in the string.

The syntax is

(?!<value>)

For example, say you wanted to prevent users from using an email address that contained "@spam.com". You could use the following RegEx:

*@(?![Ss][Pp][Aa][Mm][.][Cc][Oo][Mm]$).*

Now your regular expression validator will pass if their value does NOT match the regular expression.

Regular Expression are extremely powerful, and I encourage everyone to learn about them. If you can master them, consider yourself a superhero.

1 comment: