Tuesday, April 5, 2011

PHP Validation Question

Is there a way I can check if a user entered only 4 numbers and not 4 letters using PHP? If so how?

From stackoverflow
  • if (strlen($s) == 4 && ctype_digit($s)) {
      // ...
    }
    
    deceze : +1 for greatly underused `ctype` functions! :)
  • Alternatively you can also do:

    if(preg_match('/^\d{4}$/',$input)) {
     // valid input
    } else {
     // invalid input.
    }
    
  • ctype_digit won't work user input that has been type casted to integer/float form. Regex is just plain slow - so only use it when needed. So, with that in mind I would do something like

    $s = (string) $_POST['value'];
    if(strlen($s) === 4 AND ctype_digit($s))
    {
        // Now that it's verified as a good value
        // convert to int for the rest of the script
        $value = (int) $s;
    }
    

    This will also protect you from users passing arrays to your string checks.

    deceze : Hex notation and scientific notation `are_numeric` as well! Also, what's this about `ctype` not working and user input? That's nonsense.
    ChrisM : Of course ctype_digit will work. From the documentation: "Checks if all of the characters in the provided string, text, are numerical." This is just what the asker wants to do here.
    Xeoncross : Sorry, my bad. It's actually the other way around. `ctype_digit` doesn't work on integers which causes problems if you are correctly typecasting your values.
  • Filters may be a valid alternative, albeit being somewhat verbose. They allow you to express your validation rules like rules though, which is good:

    $isValid = filter_input(
        INPUT_POST,
        'varname',
        FILTER_VALIDATE_INT,
        array('options' => array('min_range' => 1000, 'max_range' => 9999))
    );
    

0 comments:

Post a Comment