Geeks With Blogs

News INETA Community Speakers Program WTFNext's hosting!

View Stacy Vicknair's profile on LinkedIn

WTF Next? Dev ramblings from a master of nothing.


I’ll be honest that this did happen to me, and thankfully the MSDN straightened me out.

For those of us who normally program for winforms, sometimes the switch to an ASP.NET project can prove to be a whole new world. For instance, I was working on a straightforward single page in ASP.NET 1.1 so that members of the same project could gather some information easily.

The form itself had one field, and I wanted to ensure that the field was a number only. I added a RegularExpressionValidator and pointed it to my text box, and gave the simple regex ^[0-9]+$ which should just allow 1 or more numbers to be entered. When I started testing it out, that wasn’t the case.

The validation worked properly for all cases except when the user would enter nothing. In that case, the validator just let the thing straight on through. I’m not delusional and I don’t have to write a regex every day, so I starting thinking what’s wrong with my regex? I even talked to people I trusted on ASP.NET about it, and they were mostly suggesting the regex might be wrong (from lack of familiarity with regex).

Turns out, RegularExpressionValidator will not stop the empty string. When you think about it (and I’m sure most ASP.NET developers are thinking “Duh!”) what good would regex be if you couldn’t apply it to a field, even if it wasn’t mandatory.

So, to filter out the lack of entry, add a RequiredFieldValidator to the mix. This’ll catch the contingency the regex doesn’t, and you’ll be good to go.

For more info on RegularExpressionValidator and its uses, reference the MSDN here. The first Note in the remarks highlights the information presented here.

Posted on Friday, October 10, 2008 8:45 AM VB .NET , C# .NET | Back to top

Comments on this post: RegularExpressionValidator will not stop the empty string

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Stacy Vicknair | Powered by: