1

My code is:

$user_patt = "/^[A-Za-z0-9]{8,20}$/";

however when I use the preg_match to validate the format:

if (preg_match("/user/i", $field)) {
    if (!preg_match($user_patt, $value)) {
        $error_array[] = "$value is an invalid $field";
   }
}

Then I keep getting an error for registering a name such as Granted42. Did I miss something?

BenB
  • 2,747
  • 3
  • 29
  • 54

3 Answers3

0

How about using 3 regular expressions?

if (!(preg_match('/^[A-Za-z0-9]{8,20}$/', $value) &&  
      preg_match('/[A-Z]/', $value) &&
      preg_match('/[0-9]/', $value))) 
{
    $error_array[] = "$value is an invalid $field";
}

If you must use only 1 regular expression, you can try:

if (preg_match('/^[A-Za-z0-9]*[A-Z][A-Za-z0-9]*[0-9][A-Za-z0-9]*|[A-Za-z0-9]*[0-9][A-Za-z0-9]*[A-Z][A-Za-z0-9]*/', $value)) {
    $error_array[] = "$value is an invalid $field";
}

This simply states either an upper case letter appears before a number, or the other way around, but it no longer captures the 8 to 20 characters requirement.

Fabricator
  • 12,722
  • 2
  • 27
  • 40
0

If you don't want any other character than letter and digit:

$user_patt = '/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[a-zA-Z0-9]{8,20}$/';
if (!preg_match($user_patt, $value)) {
    $error_array[] = "$value is an invalid $field";
} 
Toto
  • 89,455
  • 62
  • 89
  • 125
-1

This should work for you. I have updated it to look for 8 to 20 characters and require at least one upper, lower and digit. It will also not allow non-alphanumeric characters including white space.

$user_patt = '/^((?!.*[^a-zA-Z\d])(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,20})$/';

if (!preg_match($user_patt, $value)) {
    $error_array[] = "$value is an invalid $field";
}
V_RocKs
  • 134
  • 1
  • 13
  • I understand half of that expression, I am still very new at this what does the asterisk and the ?= mean? – Jason Cameron Jun 24 '15 at 00:54
  • Still working on why it isn't work for you. Your regex is only validating whether or not the user entered something in that has either uppercase, lowercase or numbers. It doesn't check if it has one of each. My regex does check to make sure at least one of them is present. – V_RocKs Jun 24 '15 at 01:11
  • `?= ` looks ahead trying to match `.*` any number of characters between 0 and unlimited, not including a new line. So do we have at least one capital letter? Do we have at least one lowercase letter? Do we have at least one digit? Are they within 8 to 20 character spaces? If so, we have a match. – V_RocKs Jun 24 '15 at 01:49
  • 1
    You need to anchor the regex otherwise something like `$value = 'gRa90fkgkgjgjghjhkhkhkhlgkfkfkdjfkghlhkkfadfasdfasdfasdfasdfsafs';` is valid. http://sandbox.onlinephpfunctions.com/code/cfcd9a9ed3f141f2f833e97675080a16866f7f68 – chris85 Jun 24 '15 at 02:35