Validate Email Addresses – Javascript and PHP Example

Overview – Validate Email Addresses – Javascript and PHP Example

In todays article I will show provide you with source code validate email addresses using either Javascript or PHP. It uses a regular expression to test if the string passed to is a valid email address and returns true or false in either case. It works well for me and will hopefully do the trick for you.

Javascript Example using the function: test()

<script type="text/javascript">

/* validate an email address */
function validateEmail( em ) {
	var pattern = /^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})(\.([a-z]{2,4}))*$/i;
	return (pattern.test(em)) ? true : false;
}

</script>

In order to use the javascript validate email address function, simply include the above function in your javascript or separate include file and then call it using

<script type="text/javascript">
var bValidEmail = validateEmail('somemail@example.com');
</script>

PHP Example using the function: preg_match()

<?php

/* validate an email address */
function validateEmail( $em ) {
	$pattern = '/^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})(\.([a-z]{2,4}))*$/i';
	return preg_match($pattern,$em) ? true : false;
}

?>

In order to use the php validate email address function, simply include the above function in your php or separate include file and then call it using

<?php
$bValidEmail = validateEmail('somemail@example.com');
?>