PHP: Validate an email address with regex.

Posted on January 9, 2012 by Jimmy K. in Tutorials.

Email addresses are used for everything. Registrations, usernames, lead generation… Everything. They are as unique as a telephone number or physical address and require validation just like any other piece of data.

I’ve come across a lot of poorly written email validation scripts, but this one has risen from the ashes in a blazing glory every single time. And what’s more is you can convert it to a JavaScript validation function too! ^_^

<?php

/* validate an email address. */
function jValidateEmailAddress($sInput) {
	return eregi("^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,3})$", $sInput);
}

?>

Extra credit bonus stage! I converted this function to JavaScript for you.

<script type="text/javascript">

/* validate an email address. */
function jValidateEmailAddress($sValue) {
	var $oRegExp = /^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,3})$/;
	return $oRegExp.test($sValue);
}

</script>

Tags: , ,

 
 
 

If you like this, please leave a comment.