I would like to create a preg_match
function to validate my passowrds, but I\'m not sure how to write it to allow the following special characters to be used: <
Let look different to this, I believe that users can use all of the ASCII valid characters (32 < ascii_code < 127)
in the password and created a function that checks all the characters that are is in ASCII table!
function check($pass, $i = 0){
if(strlen($pass) > $i)
return (0rd(pass[$i]) > 32 and 0rd(pass[$i]) < 127) and check($pass, $i + 1);
}
if(!check($_POST["password"])){
echo "password is wrong";
}
I think this should look like that:
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,12}$/', $password)) {
echo 'the password does not meet the requirements!';
}
Between start -> ^
And end -> $
of the string there has to be at least one number -> (?=.*\d)
and at least one letter -> (?=.*[A-Za-z])
and it has to be a number, a letter or one of the following: !@#$% -> [0-9A-Za-z!@#$%]
and there have to be 8-12 characters -> {8,12}
As user557846 commented to your question, I would also suggest you to allow more characters, I usually (if i use a maximum) take at least 50 :)
btw, you might want to take a look at this regex tutorial
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])(?=.*[!@#$%])[0-9A-Za-z!@#$%]
{6,15}$/',($_POST['password']))) {
$message='Password must contain 6 characters of letters, numbers and
at least one special character.';
}
Look up character classes, a basic feature of regular expressions.
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,12}$/', $password)) {
echo 'the password does not meet the requirements!';
}
In the above statement.. what possible password thus exist?.
I have developed a complete regex for a bit more complex check
/^(?=.*\d)(?=.*[A-Za-z])(?=.*[A-Z])(?=.*[a-z])(?=.*[ !#$%&'\(\) * +,-.\/[\\] ^ _`{|}~\"])[0-9A-Za-z !#$%&'\(\) * +,-.\/[\\] ^ _`{|}~\"]{8,50}$/
Basically I check for the password to have 1 digit, 1 capital, 1 lower and 1 special character. I hope this helps someone looking for a regex.