I already gone through many post on SO. I didn't find what I needed for my specific scenario.
I need a regex for alpha numeric string. where following conditions should be matched
Valid string:
ameya123 (alphabets and numbers)
ameya (only alphabets)
AMeya12(Capital and normal alphabets and numbers)
Ameya_123 (alphabets and underscore and numbers)
Ameya_ 123 (alphabets underscore and white speces)
Invalid string:
123 (only numbers)
_ (only underscore)
(only space) (only white spaces)
any special charecter other than underscore
what i tried till now:
(?=.*[a-zA-Z])(?=.*[0-9]*[\s]*[_]*)
the above regex is working in Regex online editor however not working in data annotation in c#
please suggest.
One problem with your regex is that in annotations, the regex must match and consume the entire string input, while your pattern only contains lookarounds that do not consume any text.
You may use
^(?!\d+$)(?![_\s]+$)[A-Za-z0-9\s_]+$
See the regex demo. Note that \w
(when used for a server-side validation, and thus parsed with the .NET regex engine) will also allow any Unicode letters, digits and some more stuff when validating on the server side, so I'd rather stick to [A-Za-z0-9_]
to be consistent with both server- and client-side validation.
Details
^
- start of string (not necessary here, but good to have when debugging)(?!\d+$)
- a negative lookahead that fails the match if the whole string consists of digits(?![_\s]+$)
- a negative lookahead that fails the match if the whole string consists of underscores and/or whitespaces. NOTE: if you plan to only disallow ____
or " "
like inputs, you need to split this lookahead into (?!_+$)
and (?!\s+$)
)[A-Za-z0-9\s_]+
- 1+ ASCII letters, digits, _
and whitespace chars$
- end of string (not necessary here, but still good to have).