desi desi - 1 year ago 131
C# Question

Regular Expression for password validation

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.


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.


Answer Source

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:


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


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:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download