Wednesday 11 March 2009

Javascript Function to Check Email Address Format using RegExp

This Javascript function performs a basic test to validate an email address.

The only true way of validating an email is to send an email and ask for a reply of some kind. This function is an initial step by making sure the format is correct.

function isEmail(e)
{
var emailPattern = new RegExp(/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/);
return(emailPattern.test(e));
}

And an example html page.

<html>
<head>
<script>

function testEmail(e)
{
if(isEmail(e))
alert('true');
else
alert('false');
}

function isEmail(e)
{
var emailPattern = new RegExp(/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/);
return(emailPattern.test(e));
}


</script>
</head>

<body>
<h1>Email RegExp Test</h1>
<input id="email" type="text"/>
<input type="button" value="Test" onclick="testEmail(document.getElementById('email').value);"/>
</body>

</html>

Validated.

No comments: