PHP Validation

Validation means testing a variable for specific requirements. If the requirements are met, validation passes, if not, validation fails. The value being tested is never altered.

Validation is used primarily when evaluating input parameters from GET or POST. PHP has provided a number of methods to work with input parameters.

Alphanumeric

ctype_alnum() will return false with blank strings.

// Validate an alphanumeric string.
function is_alphanumeric($string)
{
    if (ctype_alnum($string)) {
        return true;
    } 
    return false;
}

// test cases.
is_alphanumeric("a7jkB68J0qPfc"); // true
is_alphanumeric("A"); // true
is_alphanumeric("a"); // true
is_alphanumeric("1"); // true
is_alphanumeric("0"); // true
is_alphanumeric(1); // false
is_alphanumeric(0); // false
is_alphanumeric(''); // false
is_alphanumeric(""); // false

Email Address

function is_valid_email($email)
{
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        return false;
    }
    return true;
}

Username

  • Only alpha-numeric in addition to -.
  • First character must be a letter.
  • Can not end with -.
  • 3 character minimum.
  • 32 character maximum.
function is_valid_username($username)
{
    if (!preg_match('/^[A-Za-z][a-zA-Z0-9-]{1,30}[A-Za-z0-9]$/', $username)) {
        return false;
    }
    return true;
}