Validating Email Addresses in PHP and JavaScript

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

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>