asp.net.ph

Skip Navigation Links

Data Entry Validation

Abakada ~ Back to Basics


Checking for a valid email address

The following is a sample validation routine that uses regular expressions to test if the input of a form returns a valid e-mail address.

Now, let's see how that is done.

<script language="JavaScript1.2">
<!--
function checkEmail ( field ) {
   var isEmail = field.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
   if ( isEmail )
      alert ( 'Yes, ' + field.value + 
         ' is a valid e-mail address' );
   else {
      alert ( 'Please enter a valid email address!' );
      field.focus ( );
      field.select ( );
   }
}
//-->
</script>

<form onSubmit="checkEmail ( this.email ); return false; ">
<input type="text" name="email">
<input type="submit" value="Check">
</form> 

Before the introduction of regular expressions in JavaScript, one common way of checking if a form field contains a valid e-mail address was to test for the presence of an " @" symbol in the string, using the indexOf ( ) method.

While this provides some degree of certainty that the entry is valid, the use of regular expressions can improve on this significantly. Not only will the code be shorter, but it also executes faster. In the above example, the field output is simply compared to a regular expression pattern using the match method.

The pattern in use above was built upon the following assumptions:

  • every e-mail address has an " @" symbol in it;
  • every e-mail address has at least one alphanumeric character before the " @" symbol;
  • every e-mail address has either a two-letter country code or a .com, .net, .edu, .mil, .gov or .org suffix
  • there must be no spaces within the e-mail address.
/\b ( ^ ( \S + @ ). + ( ( \.com ) | ( \.net ) | ( \.edu ) | ( \.mil ) |
  ( \.gov ) | ( \.org ) | ( \..{ 2, 2 } ) ) $ ) \b/gi

Note that in actual use, there must be no spaces anywhere within the pattern. Also note that the the only limitation of the pattern is that it cannot verify the validity of the two-letter country code.

See Also

Validating Against Patterns ( Web Forms )   Web Forms Validation


Back to top


© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note