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

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.