Friday, June 21, 2019

Email id validation using php - Sample code

PHP - Validate E-mail

The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.  In the code below, if the e-mail address is not well-formed, then store an error message:

Sample Program: #1

$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format";
}

Sample Program: #2

// PHP program to validate email
// Function to validate email using regular expression
function email_validation($str) {
    return (!preg_match(
"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $str))
        ? FALSE : TRUE;
}
 
// Function call
if(!email_validation("author@evergreenphp.com")) {
    echo "Invalid email address.";
} else {
    echo "Valid email address.";
}

Sample Program: #3
 
$email_a = 'sir@evergreenphp.com';
$email_b = 'yourfriend';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "Email ID '$email_a' is considered valid.\n";
}

if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "Email ID '$email_b' is considered valid.\n";
} else {
    echo "Email ID '$email_b' is considered invalid.\n";
}

Popular Posts