Regex to validate password

2019-02-25 13:46发布

问题:

I've looked on here for some ideas but I still seem to be struggling with coming up with a regular expression to meet my requirements.

I need a regular expression to check a password format, the criteria are:

  • At least 1 uppercase letter
  • At least 1 number
  • Only alphanumeric characters (no special characters)
  • At least 8 characters long

The regular expression I'm using is:

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

However this is also allowing characters like !$&.

Is there a modification I need to make to this to get it to stop these special characters being accepted?

回答1:

Change the last part .{8,} to [a-zA-Z\d]{8,}

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