0

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

3 Answers 3

2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Yep, that's more straight forward than I expected it to be. Deleted my answer as I stand corrected :-)
This will allow any character in the password (as long as there is one letter/digit and on special character), because you use . at the end.
0

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 [!@#$%^&*]+.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.