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)) {
        echo "true\n";
    } else {
        echo "false\n";
    }
}

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

Email Address

$email = "john.doe@example.com";

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}