Often times when creating a webpage I'll need to do some validation on the fields. I don't always want to have to post back to the server and do server side validation, but the available validation controls may not always meet my needs:
2. CompareValidator - Compares a form field's value with the value of another form field using relations like less than, equal, not equal, etc.
3. RangeValidator - Ensures that a form field's value is within a certain range.
4. RegularExpressionValidator - Makes sure that a form field's value corresponds to a specified regular expression pattern.
5. CustomValidator - Checks the form field's value against custom validation logic that you, the developer, provide.
Descriptions found at 4GuysFromRolla.com - Using the CustomValidator Control
One such need is to check the length of a string within a field. I know this can easily be done by doing a postback and checking string.length, but I want to avoid the post back.
I know that I could use the CustomValidator and write my own function but I'm slightly too lazy to do even that.
After scouring the web looking for a solution to my laziness, I found many forums where users were wanting to use Regular Expressions (RegEx) to validate the length of the string. The answer was always, no it can't be done, no why would you want to do that, etc.
This turned my problem into one of laziness into one of "How can I check the length of a string using regular expressions?" and thus be able to use the RegularExpressionValidator provided to us.
To use regular expressions to check the length of a string you need to first decide if the length can be variable but no greater than some number, or if the length has to be exactly some number.
If the length of the string can be between 0 and x (x being any number) then you can use the following expression:
That will accept any number of characters (alpha, numeric, symbol, etc), up to x long
If you want exactly x characters you can use:
In the event that you don't want any character, and perhaps you just want alpha numeric characters instead of a period ".", you can use
You can plug your regular expression into the ValidationExpression field of the RegularExpressionValidator on your webpage.