Validating Email Addresses in PHP and JavaScript

Here are a couple of functions that I use frequently to validate the format of an email address. Both use the same regular expression, but one is written in PHP and the other in JavaScript.

In PHP

function valid_email($email) {
    return preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i', $email);
}

// Example
if( valid_email("nobody@example.com") ) echo "Valid"; else echo "Invalid";

In JavaScript

function validEmail(email) {
    return /^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i.test(email);
}

// Example
if( validEmail("nobody@example.com") ) alert("Valid"); else alert("Invalid");
Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.