PHP Form Validation: Email addresses

This entry is part 7 of 7 in the series PHP Form Validation

Checking an email address is arguably the most common form validation task for a form.

A common method is to use regular expression.

The regular expression ^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$ matches most common email addresses and fails to match common mistypings of addresses.

Use it with preg_match( ) as shown below.


// Logic to do the right thing based on
// the hidden submit_check parameter
if ($_POST['submit_check']) {
    // If validate_form( ) returns errors, pass them to show_form( )
    if ($form_errors = validate_form()) {
    } else {
} else {

// Do something when the form is submitted
function process_form()
    print 'Hello, ' . $_POST['email'];

// Display the form
function show_form($errors = '')
    // If some errors were passed in, print them out
    if ($errors) {
        print 'Please correct these errors: <ul><li>';
        print implode('</li><li>', $errors);
        print '</li></ul>';

    print <<< html_output
<form method='POST' action='$_SERVER[PHP_SELF]'>

Your email: <input type='text' name='email'>

<input type='submit' value='Say Hello'>
<input type='hidden' name='submit_check' value='1'>

// Check the form data
function validate_form()
    // Start with an empty array of error messages
    $errors = array();
    // Add an error message if the name is too short
    if (!preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $_POST['email'])) {
        $errors[] = 'Please enter a valid e-mail address';
    // Return the (possibly empty) array of error messages
    return $errors;


Series Navigation<< PHP Form Validation: Number ranges

Leave a comment

Leave a Reply