Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for password validation

Tags:

c#

.net

regex

I currently use this regular expression to check if a string conforms to a few conditions.

The conditions are string must be between 8 and 15 characters long. string must contain at least one number. string must contain at least one uppercase letter. string must contain at least one lowercase letter.

(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,15})$

It works for the most part, but it does not allow special character. Any help modifying this regex to allow special character is much appreciated.

like image 853
desi Avatar asked May 02 '11 16:05

desi


People also ask

What is regular expression for password?

$%^&(){}[]:;<>,.?/~_+-=|\]) Require that at least one special character appear anywhere in the string . {8,32} The password must be at least 8 characters long, but no more than 32 $ Match the end of the string. ^ Match the beginning of the string (?= .

How do I validate my username and password in HTML?

This can be done by document. getElementById() function, which selects an element by its id. var text1 = document. getElementById("username");


1 Answers

There seems to be a lot of confusion here. The answers I see so far don't correctly enforce the 1+ number/1+ lowercase/1+ uppercase rule, meaning that passwords like abc123, 123XYZ, or AB*&^# would still be accepted. Preventing all-lowercase, all-caps, or all-digits is not enough; you have to enforce the presence of at least one of each.

Try the following:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$ 

If you also want to require at least one special character (which is probably a good idea), try this:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$ 

The .{8,15} can be made more restrictive if you wish (for example, you could change it to \S{8,15} to disallow whitespace), but remember that doing so will reduce the strength of your password scheme.

I've tested this pattern and it works as expected. Tested on ReFiddle here: http://refiddle.com/110


Edit: One small note, the easiest way to do this is with 3 separate regexes and the string's Length property. It's also easier to read and maintain, so do it that way if you have the option. If this is for validation rules in markup, though, you're probably stuck with a single regex.

like image 127
Justin Morgan Avatar answered Oct 19 '22 20:10

Justin Morgan