PHP regex for password validation

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

I not getting the desired effect from a script. I want the password to contain A-Z, a-z, 0-9, and special chars.

  • A-Z
  • a-z
  • 0-9 >= 2
  • special chars >= 2
  • string length >= 8

So I want to force the user to use at least 2 digits and at least 2 special chars. Ok my script works but forces me to use the digits or chars back to back. I don't want that. e.g. password testABC55$$ is valid - but i don't want that.

Instead I want test$ABC5#8 to be valid. So basically the digits/special char can be the same or diff -> but must be split up in the string.

PHP CODE:

$uppercase = preg_match('#[A-Z]#', $password); $lowercase = preg_match('#[a-z]#', $password); $number    = preg_match('#[0-9]#', $password); $special   = preg_match('#[\W]{2,}#', $password);  $length    = strlen($password) >= 8;  if(!$uppercase || !$lowercase || !$number || !$special || !$length) {   $errorpw = 'Bad Password'; 

回答1:

Using "readable" format (it can be optimized to be shorter), as you are regex newbie >>

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

Add your special character set to last [...] in the above regex (I put there for now just -+%#).


Explanation:

^                              - beginning of line/string (?=.{8})                       - positive lookahead to ensure we have at least 8 chars (?=.*[A-Z])                    - ...to ensure we have at least one uppercase char (?=.*[a-z])                    - ...to ensure we have at least one lowercase char (?=.*\d.*\d.*\d                - ...to ensure we have at least three digits (?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])                                 - ...to ensure we have at least three special chars                                     (characters other than letters and numbers) [-+%#a-zA-Z\d]+                - combination of allowed characters $                              - end of line/string 


回答2:

((?=(.*\d){3,})(?=.*[a-z])(?=.*[A-Z])(?=(.*[!@#$%^&]){3,}).{8,}) 

test$ABC5#8 is not valid because you ask more than 2 digits and spec symbols

A-Z a-z 0-9 > 2 special chars > 2 string length >= 8 


回答3:

For matching length of string including special characters:

$result = preg_match('/^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[^A-Za-z\d])[\s\S]{6,16}$/', $string);

Answer explained: https://stackoverflow.com/a/46359397/5466401



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!