Regular expression to not allow users to enter NA or N/A or na or n/a
I have a text box and users are entering na rather than supplying the specified data. How can explicitly not allow them to enter na in the field? I want to use an asp r开发者_如何学运维egularexpressionvalidator.
^(?!\s*n\s*/?\s*a\s*$).*
will match (and return the input string) if the user enters anything except n/a
and fail otherwise. All the variations in your questions are covered if you select case-insensitive matching (in .NET, this is done using the option RegexOptions.IgnoreCase
). Also, any amount of whitespace will be ignored so the user can't simply type n / a
.
Why use regex to solve this when you can solve it with a simple if statement?
if (input.ToLower().Trim() != "na" && input.ToLower().Trim() != "n/a")
{
// Continue processing
}
You can't do this with RegularExpressionValidator because it will error when the pattern is not matched. There is no way to invert the RegularExpressionValidator to give an error condition when the pattern is matched.
You can use a CustomValidator to get this done and 4 Guys From Rolla wrote an tutorial on how to do this a while ago or you can get some 3rd part validators like those from Peter Blum.
Before you invest to much time in it you should consider the comment from @bemace. If you do implement this you will only get a new kind of "garbage in" instead of n/a.
Case insensitivity can be toggled by ?i: token, so the resulting regex can be like that:
(?i:^n\/a$)
Update: added parentheses after Alan's comment.
Ryan makes a good point - but if you're dead-set on using regex, this should do the trick (make sure you mark it as case insensitive):
^n\/?a$
精彩评论