Monday, July 28, 2014

My Javascript Way to Check the Validity of an Email Address Input

Before sending an email address input from a submitted form to the server to verify, it is better to perform a simple check on the email address format for any possible typo. This will save some server bandwidth as Javascript is capable of catching some obvious email format errors.

The following Javascript codes/function are used:


function emailError() {

 if (document.userForm.em.value.match(/(\w+\@\w+\.\w+)/) == null) {
  return true;

 return false;

if (emailError()) { alert('Invalid Email Format!'); }


Assume the name of your HTML form is 'userForm' and em is the name of the email input. The emailError() function is making use of the Javascript .match() function to match the pattern of \w+\@\w+\.\w+. If there is a mismatch, an error (true) will be returned to signify an email format error. Please also note that this function will also treat as valid although the code can only match the Since the match content is not important, the ab. before the cd will be ignored without affecting the result of the emailError() function.

No comments:

Post a Comment