I'm trying to validate a password with PHP and I want to use the same Regex with Javascript, In my PHP I'm getting error when I'm trying to use the following regex. (Warning: filter_var(): Compilation failed: range out of order in character class at offset 14)
/^[a-zA-Z0-9_-\]\[\?\/<~#`!@\$%\^&\*\(\)\+=\}\|:\";\',>\{]{4,20}$/
if (!filter_var($password,FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z0-9_-\]\[\?\/<~#`!@\$%\^&\*\(\)\+=\}\|:\";\',>\{]{4,20}$/")))){
$errors .= "Please enter a valid password.";
}
I want the password to have 0-9
, a-zA-Z
and these characters ] [ ? / < ~ # ! @ $ % ^ & * ( ) + = } | : " ; ' , > { space
] [ ? / < ~ # ! @ $ % ^ & * ( ) + = } | : " ; ' , > { space
] [ ? / < ~ # ! @ $ % ^ & * ( ) + = } | : " ; ' , > { space
plus `
I want to use the regex for front and back ends.
Take a look at this "modular" regEx
/(?=.*\\d)(?=.*[az])(?=.*[AZ]).{8,}/.test(password)
this password should have:
(?=.*\\d)
= digits (?=.*[az])
= small letters (?=.*[AZ])
= cap. letters .{8,}
= at least 8 chars long Special chars part: taken from one of the answers above thanks @stribizhev
(?=.*[?\\/<~#`!@$%^&*()+=}|:\\";\\',>{ -])
= special chars So you end up with:
/(?=.*\\d)(?=.*[az])(?=.*[AZ])(?=.*[?\\/<~#`!@$%^&*()+=}|:\\";\\',>{ -])/.test(password)
to force minimal lenght .{n,} n = lenght
/(?=.*\\d)(?=.*[az])(?=.*[AZ])(?=.*[?\\/<~#`!@$%^&*()+=}|:\\";\\',>{ -]).{8,}/.test(pass)
/^[a-zA-Z0-9_\]\[\?\/\<\~\#\`\@\$%\^&\*\(\)\+=\}\|:\";\'\,>\{]{4,20}$/
You had an un-escaped hyphen in your first character set, and you needed to escape the comma.
Edit: Escaped a few other metacharacters.
You can use
^[a-zA-Z0-9_\]\[?\/<~#`!@$%^&*()+=}|:\";\',>{ -]{4,20}$
^^
Note the "smart" position of the hyphen at the end of the character class, and in JS and PHP you won't have to escape it.
I see your regex is missing a space, I added it, too.
Note that inside a character class, a lot of special characters are treated as literals, and do not have to be escaped. I removed escape symbols from those that do not need escaping.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.