Regular Expression for a password with at least 8 characters and at least 1 non-alphanumeric character(s)

16.4k views Asked by At

I am trying to make a check in PHP if a user changes their password their new password must be 8 or more characters and with at least 1 non-alphanumeric password. How should I check this and what would the regex be?

Checking the length is the easy part strlen >= 8. My problem is regular expressions. I really have no clue about regular expressions even after years of studying computer science.

Thanks

6

There are 6 answers

10
nickb On BEST ANSWER

Try something like this to check if they used non-alphanumeric characters:

if( !preg_match( '/[^A-Za-z0-9]+/', $password) || strlen( $password) < 8)
{
    echo "Invalid password!";
}

The if statement will evaluate to true if the $password does not contain at least one of the characters not in the list (alphanumeric characters).

5
John Conde On

This should work (untested)

if (preg_match('/^(?=.*[\W])(?=[a-z0-9])[\w\W]{8,}$/i', '123abc!$'))
{
    //error
}

It makes sure the password is 8 characters long and has at least one special character

1
Jonathan S. On

If you're checking the string length with strlen/mb_strlen, you can simply write a regular expression to match any non-alphanumeric character. If it matches one (or more), you're good. For example:

$password = 'asdf123!';

if(mb_strlen($password) >= 8 and preg_match('/[^0-9A-Za-z]/', $password))
{
    // password is valid
}
2
Mathieu Dumoulin On

To my knowledge, you can't achieve this because it's a composite condition scenario.

What you'd need to do is do it in a three step fashion:

$has8characters = (mb_strlen($_REQUEST['password']) >= 8);
$hasAlphaNum = preg_match('b[a-z0-9]+bi', $_REQUEST['password']);
$hasNonAlphaNum = preg_match('b[\!\@#$%\?&\*\(\)_\-\+=]+bi', $_REQUEST['password']);

This wasn't tested, but you are pretty close of what you want to achieve with this...

Good luck

0
Andrew Willis On

Try this.

~^(.*[\W]+.*){8,}$~
  • .* looks for any character 0 or more times
  • [\W]+ matches at least one non-word character
  • {8,} matches the bracketed value only if the length is 8 or more characters
  • ^ $ match the start and end of the string
0
Jomari Benito On

This solves it. Have a try!

if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,}$/', $pass)) {
  echo "Password does not meet the requirements! It must be alphanumeric and atleast 8 characters long";
}