Jump to content

Regex, what's going wrong? (I'm new to Regex)


Far Cry

Recommended Posts

function validPassword($password)
{

$isValid = false;

if(strlen($password) >= 6){

if(preg_match('/^[a-zA-Z0-9]{1,}$/',$password)){
  $isValid = true;
}
else{
echo"<center><font color=\"red\">Your password must have at least one number and at least one upper and lower-case letter!</font></center>";
$isValid = false;
}
}
  else{
  echo"<center><font color=\"red\">Your password must contain at least six (6) characters!</font></center>";
  $isValid = false;
  }
  return $isValid;
}

 

The above code is supposed to validate a password. If (as seen in the code), the string is less than six characters, the else statement executes no problem. However, the else statement for the if statement (preg_match('/^[a-zA-Z0-9]{1,}$/',$password) does not execute, even if the string is valid.

 

I cannot figure this out, thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/239491-regex-whats-going-wrong-im-new-to-regex/
Share on other sites

If you want the password to contain at least 1 number, 1 upper-case letter, and 1 lower-case letter it seems like you would need to set the test up differently. Maybe something like:

 

<?php
...

if(!preg_match('/[a-z]+/',$password)) {
     echo"<center><font color=\"red\">Your password must have at least one lower-case letter!</font></center>";
     $isValid = false;
} elseif(!preg_match('/[A-Z]+/',$password)) {
     echo"<center><font color=\"red\">Your password must have at least one upper-case letter!</font></center>";
     $isValid = false;
} elseif(!preg_match('/[0-9]+/',$password)) {
     echo"<center><font color=\"red\">Your password must have at least one number!</font></center>";
     $isValid = false;
} else {
     $isValid = true;
}

...
?>

 

 

Note that the code is untested.

  Quote

If you want the password to contain at least 1 number, 1 upper-case letter, and 1 lower-case letter it seems like you would need to set the test up differently. Maybe something like:

 

<?php
...

if(!preg_match('/[a-z]+/',$password)) {
     echo"<center><font color=\"red\">Your password must have at least one lower-case letter!</font></center>";
     $isValid = false;
} elseif(!preg_match('/[A-Z]+/',$password)) {
     echo"<center><font color=\"red\">Your password must have at least one upper-case letter!</font></center>";
     $isValid = false;
} elseif(!preg_match('/[0-9]+/',$password)) {
     echo"<center><font color=\"red\">Your password must have at least one number!</font></center>";
     $isValid = false;
} else {
     $isValid = true;
}

...
?>

 

 

Note that the code is untested.

Thanks! Works great! :-)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.