Asp.NET Regular Expression Validator – Faulty?

May 13, 2009

I’ve just spent the best part of a day trying to figure out what was wrong with a web form I put together. I needed to prevent users from entering anything other than numbers into the box. I knew a RequiredFieldValidator wouldn’t work – That would allow any character. I then tried the RangeValidator – Entering a minimum value of 1 and a maximum value of 999999 did not work – The page was till posted back if the box was empty – Potentially expected functionality as the value was null.

So – I next thought I would try the RegularExpressionValidator – I set about putting together a RegEx that would require the users to enter a number – Anything else, including null would be invalid and cause an error to display.

After some amount of head scratching and googling, I found an MSDN page which states:
‘It will never be activated by an empty string in the control it is validating. Only the RequiredFieldValidator catches empty strings’

So, if the control value is empty, the value is not validated against the regular expression! What a load of rubbish! Surely this is flawed functionality?

Take a very simple regular expression: ^.+$ – Which equates to ‘One or more of any character’. If you run this against a TextBox, and try submitting your form with nothing entered, the validator will not fire and the form will submit!

So, whats the solution:

a) Use a CustomValidator control, running against your own RegEx test
b) Use a combination of both RequireField and RegularExpression validators (Perhaps wrapped into a custom control)

I’ve settled for option B – I’m not happy having an additional control on the page though!

So, is this behaviour of the RegularExpressionValidator by design? Or is it faulty? Comments welcome!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: