How to validate email format via JavaScript


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

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. <form name="myForm" method="POST" action="myTargetFile" onSubmit="return checkEmail()">
    
  2. Email: <input type="text" name="email1">
    
  3. <p><p>
    
  4. Please type in your email again: <input type="text" name="email2">
    
  5. <p><p>
    
  6. <input type="submit" value="Submit">
    
  7. </form>

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers!





Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

12 thoughts on “How to validate email format via JavaScript”

  1. Here is another good function for email check…

    function validateEmail(elementValue){
    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    return emailRegEx.test(elementValue);
    }

    :)

  2. 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!

    1. 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?

      1. 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!

  3. 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.

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

  4. 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.

    1. 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!

  5. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *