1
votes

I'm trying to create a Regex for an html5 pattern in a password input.

The password must contain at least:

  • 1 uppercase letter
  • 1 lowercase letter
  • 1 number
  • 1 special character
  • 8-20 characters
  • Must not start or end with a special character

Any help appreciated

1
Don't validate a password in HTML. That's pretty much the worst place you could do this.ctwheels
Just out of curiosity, why can't your passwords start/end with a special character? This seems like really weird logic to me.ctwheels
It’s only inline validation. Server side will take care of the heavy lifting. With regards to the why of a special character at the end or beginning... sorry no clue, they haven’t told me the reasons.C. Unit
You and your team should take a look at Reference - Password Validation.ctwheels
If you need to do some sort of validation client side just use AJAX to call your server-side validation script. No need to create 2 regular expressions. Anything you do in HTML patterns right now can be undone and they also don't allow Unicode if you're using [a-z] to ensure lowercase letters (same goes for uppercase letters, numbers and special characters. Adding the logic that doesn't allow a password to begin and end with a special character also reduces the number of potential passwords, thus making your systems less secure. Your team should definitely re-evaluate password policies.ctwheels

1 Answers

4
votes

It's not that hard:

(                   # Start of group
    (?=.*\d)        #   must contain at least one digit
    (?=.*[A-Z])     #   must contain at least one uppercase character
    (?=.*[a-z])     #   must contain at least one lowercase character
    (?=.*\W)        #   must contain at least one special symbol
    \w
       .            #   match anything with previous condition checking
        {6,18}      #   length is  characters
    \w 
)                   # End of group

In one line:

((?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*\W)\w.{6,18}\w)

If you do not like \w which is equal to [a-zA-Z0-9_] replace it with that group and remove the underscore.

However, I fully support ctwheels' argument.