PHP email validation with filter_var and regular expression


Here, In this post i will show you how to validate email addresses with PHP filter_var and regular expression just to ensure that the part after the @ contains a dot.

Use of filter_var with regular expression and check the domain part contains a dot

Here's the code to run this test, which I've put into a function to make it easy to call each time:

function validateEmailAddress($email) {

    

    // Remove all illegal characters from email

    $email = filter_var($email, FILTER_SANITIZE_EMAIL);

    

    return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email);

}


filter_var does most of the grunt work to ensure the full email address, including the domain name part, is valid. The regular expression then checks to make sure the domain part after the @ symbol contains a . somewhere. The regular expression doesn't need to do any further checking (e.g. to make sure there are characters after the .) because the filter_var function has already done this.

Tests

Here's some tests to show the above working where 1 will be echoed if it's valid, 0 if not. The result is shown at the end of the line after the // comment.

echo (int) validateEmailAddress('chris@example'); // 0

echo (int) validateEmailAddress('chris@example.'); // 0

echo (int) validateEmailAddress('chris@example.com'); // 1

echo (int) validateEmailAddress('chris@example.com.'); // 0

echo (int) validateEmailAddress('chris@example@example.com'); // 0

echo (int) validateEmailAddress('chris#example.com'); // 0

echo (int) validateEmailAddress('chris@my.multiple.dot.example.com'); // 1

Post a Comment

0 Comments