I am new to Asp.Net and I want to validate SSN using regularexpressionvalidator. In the regularexpressionvalidator I gave regularexpression as :
ValidationExpression="\d{3}-\d{2}-\d{4}"
My regular expression works fine. It says 3 digits then – then 2 digits then – then 4 digits.
However I also want the regular expression to succeed when the textbox is full empty or the textbox contains just:
_ _ – _-_ _ _ _
where _ stands for “space” (not _. I’ve shown _ just so editor can show it up on SO).
How can I do that with regularexpressionvalidator?
This pattern should meet all three use cases:
I used literal spaces in a character array above rather than
\s, because\swould have also matched tabs, newlines, and other whitespace characters. Also, it is important to keep the space and digit tests separate, not in the same subpattern, otherwise you’d match junk input like123-__-6_8_.Edited: @Dan correctly noted in his answer that the ^ and $ should surround the entire pattern so we match the entire string, not just find an SSN somewhere within it.