Reputation:
I'm new to .net and I'm stuck with a problem I want to validate my password field ,The password must be a alphanumericstring with special symbols and I wrote a code for that which is given below
[Required(ErrorMessage = "Password is required")]
[RegularExpression(@"^[a-zA-Z0-9~!@#$%^&*]{8,15}$", ErrorMessage = "Password is not in proper format")]
public virtual string Password { get; set; }
But its not working if the password length is greater than 8 then its gives green signal for the string even its only contain alphabets. How can I overcome this problem
Upvotes: 0
Views: 2878
Reputation: 32797
You can use this regex
^(?=.*[a-zA-Z\d])(?=.*[~!@#$%^&*])[a-zA-Z\d~!@#$%^&*]{8,15}$
---------------- -----------------
| |->match further only if there's any one of [~!@#$%^&*]
|-> match further only if there's any one of [a-zA-Z0-9]
Upvotes: 2
Reputation: 92976
You can use positive lookahead assertions to ensure certain conditions on your string:
[RegularExpression(@"(?=.*[a-zA-Z0-9])(?=.*[~!@#$%^&*])[a-zA-Z0-9~!@#$%^&*]{8,15}", ErrorMessage = "Password is not in proper format")]
When you use the Regular Expression validator, you don't need anchors, the regex is automatically matched against the whole input string.
(?=.*[a-zA-Z0-9])
is checking from the start of the string, that there is a letter or a digit somewhere in the string.
(?=.*[~!@#$%^&*])
is checking from the start of the string, that there is a special character somewhere in the string.
[a-zA-Z0-9~!@#$%^&*]{8,15}
is then actually matching the string, allowing only the allowed characters.
Upvotes: 0
Reputation: 5401
The thing is - right now you're just checking for a string with length 8 to 15 that is made up out of these characters. If you want to make sure you have at least one special character, you need something like [!@#$%^&*]+.
Upvotes: 0