Validating Email Addresses in PHP and JavaScript

A Message From A Beautiful Site, LLC.
We spent over a year redeveloping Surreal CMS to make it the best hosted content management system out there. If you have a website, it’s worth checking out. Learn More »

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.

Verifying Email Addresses in PHP

function validate_email($email) {
    if( preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $email) ) {
        return true; // Valid
    } else {
        return false; // Invalid
    }
}

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

Verifying Email Addresses in JavaScript

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

// Example
if( validateEmail("nobody@example.com") ) alert("Valid"); else alert("Invalid");
If you enjoyed this article, please share it with a friend!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>