Tutorial Ref.com

Javascript Validate Email: Form Validation with Regex

This is a simple tutorial on using javascript to validate an email in a form submission. Here is the html form:

1
2
3
4
5
6
7
8
9
10
11
<form id="register" method="post" action="connect2.php" onsubmit="return checkWholeForm(this)">
    <fieldset>
        <table>
            <tr>
                <td><label style="padding-left:20px;" for="email">email:</label></td>
                <td><input type="text" name="email" id="email" size="30" maxlength="45" /></td>
                <td id="errorMesEmail"></td>
            </tr>
        </table>
    </fieldset>
</form>

I omitted all other fields for simplicity's sake. There are a couple of things to note. The "onsubmit" attribute of the

tag calls a checkWholeForm() function. This is a Javascript function that we'll come back to in a moment. The other thing to note is the last tag which contains an "id" attribute as "id='errorMesEmail'" which will display the error if the validation check does not pass.

Here is the Javascript checkWholeForm() function:

1
2
3
4
5
6
function checkWholeForm(theForm) {
    cEmailRegex = checkEmailRegex(theForm.email.value);
    if (cEmailRegex == "") {
               return false;
    }
}

The checkWholeForm() function checks all the form fields; however, I've only included the email part of the form for simplicity. The checkEmailRegex checks the email and validates it against a regular expression (regex) pattern. If the validation fails then the checkEmailRegex() function will return false to the checkWholeForm() function. In order to prevent the submission of the form if the email does not validate against the regular expression then the checkWholeForm() needs to return false which is denoted in the if clause as:

1
if (cEmailRegex == "")

So now let's look at the checkEmailRegex() function. The following from the checkWholeForm() function will call the checkEmailRegex() function and pass the email's value as:

1
checkEmailRegex(theForm.email.value);

Here is the checkEmailRegex() in its entirety:

1
2
3
4
5
6
7
8
9
10
11
12
function checkEmailRegex(emailVal) {
this.errorMes = document.getElementById("errorMesEmail"); // dom to display error message
var emailRegex = /[_+a-zA-Z0-9-]+(\.[_+a-zA-Z0-9-])*@[_+a-zA-Z0-9-]+(\.([a-zA-Z]{2,}))+/i;
 
    if (emailRegex.test(emailVal) != true) {
     error = "The email you entered does not look like a valid email address.";
     this.errorMes.innerHTML = error;
     return false;
     } else {
         return true;
     }
}

The second line:

1
this.errorMes = document.getElementById("errorMesEmail");

will get the element by the "id" and place in in the function variable "this.errorMes". This "id" will be used to place the error message if there are any.

The third line:

1
var emailRegex = /[_+a-zA-Z0-9-]+(\.[_+a-zA-Z0-9-])*@[_+a-zA-Z0-9-]+(\.([a-zA-Z]{2,}))+/i;

is the crux of the function which contains the regular expression. The forward slash (i.e. /) tells the regex that it's the beginning of the regex pattern. The last forward slash (i.e. /) tells the regex pattern that it's the end of the pattern. So let's go through the pattern one section at a time.

The first part:

1
[_+a-zA-Z0-9-]

is search for any underscore, plus sign, lower-case characters or uppper-case characters, digits 0 to 9 or negative sign. The plus sign (i.e. +) immediately after this regex is concantenation of the next set of regex pattern which is:

1
(\.[_+a-zA-Z0-9-])*

Notice the open and closed brackets and the asterisk (i.e. *) at the end of the closed bracket. The asterisk indicates search for the regex pattern in between the previous open and closed brackets and allow this regex pattern to occur one or more times. The only difference between this regex pattern and the first regex pattern is the backward slash and dot (i.e. \.). We need to escape certain characters in order for the regex pattern to interpret the character as a literal. In other words, in order read the character as a dot (i.e. .). If we did not escape the dot with a backslash (i.e. \.) and simply used a dot (i.e. .) then the regex would search for any single character (excpet a new line character such as \n). So this regex pattern is searching for a dot with any letter (lower-case or upper-case), any digit, or any underscore, plus or negative sign and this set of characters could occur zero or more times.

The the first two regex patterns we just dissected could be matched by:

  • john.smith
  • john1967
  • johnsmith.1967
  • john_smith.doe
  • john-smith.doe1967

So the next set of regex we'll look at is:

1
@[_+a-zA-Z0-9-]+

Pretty straight forward as already discussed. The only difference is the at sign (i.e. @). The plus sign (i.e. +) at the end is a concatenator.

Here's the last set of the regex pattern:

1
(\.([a-zA-Z]{2,}))+

The backslash and dot (i.e. \.) is an escaped dot as just explained. The next open and closed bracket set:

1
([a-zA-Z]{2,})

means any lower-case or upper-case characters can occur two or more times. The two or more times is represented as a curly open and closed bracket with the number 2 and a comma (i.e. {2,}). The plus sign here is different and does not mean concatenation. The plus sign (i.e +) here means the regex pattern in the previous open and closed bracket can occur one or more times. The difference between this plus sign and the others is that this plus sign occurs after a regular closed bracket rather than a square closed bracket. The regular closed bracket and a plus sign (i.e. )+) will be interpreted as matching the regex pattern within the immediate previous open and closed bracket to occur one or more times.

So the following regex pattern:

1
@[_+a-zA-Z0-9-]+(\.([a-zA-Z]{2,}))+

will match:

  • @tutorialref.co.uk
  • @tutorialref.com
  • @tutorialref.jp
  • @tutorialref.cn
  • @myisp123.com
  • @my-isp123.org

This is a simple example of validating email in an html form with Javascript regex pattern but hopefully you`ll be on your way to a greater understanding of Javascript form validations.

TutorialRef.com - tutorials, guides, how-tos, helps