Check Email Address with JavaScript and Regular Expressions

Check Email Address with JavaScript and Regular Expressions

A while ago I put up a Password Strength Checker using JavaScript and Regular Expressions. On that same note, you can also check the structure of an email address utilizing the same regular expression (regex) methodology.

If your form element has the id=”emailaddress” and you add a form onSubmit=”return checkEmail();“, this is a Javascript function that you can utilize to return an alert if the email address has a valid structure or not:

<script language="javascript">
function checkEmail() {
var email = document.getElementById('emailaddress');
var filter = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>

The function validates the contents of the email to that of the filter. If the comparison fails, it pops up an alert and returns the focus back to the email address field!