Random Snippets

  • Home
  • Sequence analysis blog
  • About
  • Categories
    • javascript
    • mysql
    • php
  • Subscribe via RSS

How to validate email format via JavaScript

April 1st, 2008  |  Published in javascript  |  11 Comments


This JavaScript demo verifies that an email address is in the correct format and that the user has typed in the same address in both fields to prevent mistyping of the address. I have borrowed the regex for verifying the correct email format from a different site.

Demo
Email:

Please type in your email again:


Here is the plain HTML of the form. Please note that I have removed the action attribute because this is only a demo and we are only concerned with the client-side verification of the JavaScript function.

1
2
3
4
5
6
7
<form name="myform">
Email: <input type="text" name="email1">
<p><p>
Please type in your email again: <input type="text" name="email2">
<p><p>
<input type="button" onClick="verifyEmail();" value="Check Email Address">
</form>

Nothing exciting here except in line 6 where the onClick event is triggered when the user clicks on the button. This event will launch the verifyEmail() JavaScript function which will check the user input of the email address.

Here is the code for the verifyEmail() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function verifyEmail(){
var status = false;     
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
     if (document.myform.email1.value.search(emailRegEx) == -1) {
          alert("Please enter a valid email address.");
     }
     else if (document.myform.email1.value != document.myform.email2.value) {
          alert("Email addresses do not match.  Please retype them to make sure they are the same.");
     }
     else {
          alert("Woohoo!  The email address is in the correct format and they are the same.");
          status = true;
     }
     return status;
}

This function will return a false value if the user does not type in an email address in the correct format or if the user fails to type in the same email address in both fields. If the email addresses passes both these tests, then the function will return a true value.

The regex for validating the correct email format in line 2 has been borrowed and edited slightly by adding the i flag so that the regex is case-insensitive.

The if block in lines 3-6 checks to see if the email address in the first field passes the regex check by invoking the search() method on our email string value. This method accepts regex expressions as arguments to check the string and returns the position of the specified value in the string or a -1 if no match was found. If the search() method returns a -1, then an alert would tell the user that an invalid email address has been entered and returns a false value.

Lines 7-10 checks to see if the user has entered the same string in both email fields. This is done by a simple equality check on the string values. If the strings are different, an alert warns the user that the email addresses are not the same and returns a false value.

If we have passed the two tests, then else block in lines 11-14 gets executed. An alert tells the user that he or she has done a good job and the function returns a true value so that you can continue with the form submission.

Ideally, you would have this function run during the onSubmit attribute for the form tag. This way, the form will get submitted when the checkEmail() function returns a true value. Here is an example of how your form would look like:

1
2
3
4
5
6
7
<form name="myForm" method="POST" action="myTargetFile" onSubmit="return checkEmail()">
Email: <input type="text" name="email1">
<p><p>
Please type in your email again: <input type="text" name="email2">
<p><p>
<input type="submit" value="Submit">
</form>
Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Responses

Feed Trackback Address
  1. marie says:

    July 31st, 2008 at 1:26 pm (#)

    In my HTML script, I ask user to enter his/her first and last name, address, state, etc. If user skips it, I’d like to display an “alert” to remind for input data. How to detect if the input is empty or just blank spaces are entered.

    [Reply]

  2. marie says:

    July 31st, 2008 at 3:13 pm (#)

    Please ignore my previous email about 2 hours ago.
    My question really is — how to detect/verify that my user did not enter anything in a input file.
    I use the
    …input_name.value == null or
    …input_name.value == “” none of them works.
    Your help is very much appreciated.

    [Reply]

    Knix reply on July 31st, 2008 3:44 pm:

    Hi Marie,

    You can try checking the string length of the input value:


    if (input_name.value.length() > 0) {
    do something...
    }

    I hope this information helps. Good luck!

    [Reply]

  3. some says:

    July 31st, 2008 at 4:26 pm (#)

    That:
    function verifyEmail(){
    …
    if (…) {
    …
    return false;
    }
    else if (…) {
    …
    return false;
    …

    That code is not well structured.
    it should be one, and only one return from the function.

    [Reply]

    Knix reply on July 31st, 2008 4:43 pm:

    You are right. Thanks for pointing that out. I have restructured the code accordingly and it looks much better. Thanks for the suggestion.

    [Reply]

  4. Peter Breyfoge says:

    October 15th, 2008 at 7:44 am (#)

    How about checking that there is at least one @ sign and it is followed by at least one period and a proper domain name?

    [Reply]

    Knix reply on October 15th, 2008 11:58 pm:

    Hi Peter,

    The regular expression in line 3 of the verifyEmail function does just that and even checks the alias.

    [Reply]

  5. John says:

    April 17th, 2009 at 4:02 am (#)

    Hello,
    Can u give any furhter explanation about the expression on line 3:

    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

    My actual question is how can i format a string?

    Thx!

    [Reply]

    Knix reply on April 17th, 2009 9:12 am:

    Hi John,

    Here is the breakdown of the regex:

    ^ = Matches the beginning of the string.

    [A-Z0-9._%+-] = Bracket expression that will match any letter(A-Z), any number (0-9), dot (.), underscore (_), percent sign (%), plus(+), and minus (-).

    + = This will match the preceding element, in this case the bracket expression, 1 or more times. In summary the bracket expression with the (+) will match a person’s email alias.

    @ = Match the (@) symbol in the email address.
    [A-Z0-9.-] = Bracket expression that will match any letter(A-Z), any number (0-9), dot (.), and minus (-).

    + = This will match the preceding element, in this case the bracket expression, 1 or more times.

    \. = The dot (.) in this case is matched and it is escaped with the backslash (\) because the dot by itself is used to match any single character when used in a regex (when it is outside of a bracket expression).

    [A-Z] = Bracket expression that will match any letter(A-Z).

    {2,4} = Matches the preceding element at least 2 times and not more than 4 times. In summary the bracket expression with the ({2,4}) will match the top-level domain name such as com, net, or info.

    I do not understand what you mean by “format a string” though. Can you please expand on that?

    [Reply]

    John reply on April 17th, 2009 9:59 am:

    That was really helpful, thank you!

    I’m working on a project where i need to “format” the input string from html Text Inputs in javascript, that is what i meant. I needed the email format u mentioned and i also needed a regex that applies to numbers from 1 to 100.

    So i came up with:
    var ageFormat=/\d{1,3}/g;
    which applies to 1 to 3 digit number, and then an If statement to restrict the numbers between 1 and 100.

    Thanks again!

    [Reply]

  6. hani says:

    December 3rd, 2009 at 9:29 am (#)

    thanks^_^

    [Reply]

Comments or feedback...

If you have any demos that you would like to request, please do so.

Click to cancel reply

Recent Posts

  • Sorting 2D associative arrays in PHP
  • Dynamic or on-the-fly percentage calculations with JavaScript
  • The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
  • How to randomly order or select rows in a MySQL query
  • How to convert MySQL timestamp to PHP date type

Recent Comments

  • Anders K on Simulate a button click via JavaScript
  • john on How to find and replace text dynamically via JavaScript
  • Eiolon on How to hide, show, or toggle your div
  • Use label as distant button in HTML – Community – travellin' meets real life on Simulate a button click via JavaScript
  • gaurav on Simulate a button click via JavaScript

Archives

Categories

  • javascript
  • mysql
  • php

©2010 Random Snippets