[javascript] Validate email address textbox using JavaScript

I have a requirement to validate an email address entered when a user comes out from the textbox.
I have googled for this but I got form validation JScript; I don't want form validation. I want textbox validation.
I have written below JScript but "if email invalid it's not returning the same page".

 function validate(email) {

            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            //var address = document.getElementById[email].value;
            if (reg.test(email) == false) 
            {
                alert('Invalid Email Address');
                return (false);
            }
 }

This question is related to javascript

The answer is


Assuming your regular expression is correct:

inside your script tags

function validateEmail(emailField){
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(emailField.value) == false) 
        {
            alert('Invalid Email Address');
            return false;
        }

        return true;

}

in your textfield:

<input type="text" onblur="validateEmail(this);" />

You should use below regex which have tested all possible email combination

     function validate(email) {
            var reg = "^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$";
            //var address = document.getElementById[email].value;
            if (reg.test(email) == false) 
            {
                alert('Invalid Email Address');
                return (false);
            }  
     }

Bonus tip if you're using this in Input tag than you can directly add the regex in that tag example

<input type="text"  
       name="email" 
       class="form-control"
       placeholder="Email" 
       required 
       pattern="^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$"/>

Above you can see two attribute required & pattern in

required make sure it input block have data @time of submit &
pattern make sure it input tag validate based in pattern(regex) @time of submit

For more info you can go throw doc


<h2>JavaScript Email Validation</h2>

<input id="textEmail">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo" style="color: red;"></p>

<script>
function myFunction() {
    var email;

    email = document.getElementById("textEmail").value;

        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(textEmail.value) == false) 
        {
        document.getElementById("demo").style.color = "red";
            document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
            alert('Invalid Email Address ->'+email);
            return false;
        } else{
        document.getElementById("demo").style.color = "DarkGreen";      
        document.getElementById("demo").innerHTML ="Valid Email ->"+email;
        }

   return true;
}
</script>

enter image description here

<!DOCTYPE html>
    <html>
    <body>

    <h2>JavaScript Email Validation</h2>

    <input id="textEmail">

    <button type="button" onclick="myFunction()">Submit</button>

    <p id="demo" style="color: red;"></p>

    <script>
    function myFunction() {
        var email;

        email = document.getElementById("textEmail").value;

            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

            if (reg.test(textEmail.value) == false) 
            {
            document.getElementById("demo").style.color = "red";
                document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
                alert('Invalid Email Address ->'+email);
                return false;
            } else{
            document.getElementById("demo").style.color = "DarkGreen";      
            document.getElementById("demo").innerHTML ="Valid Email ->"+email;
            }

       return true;
    }
    </script>

    </body>
    </html> 

The result in isEmailValid can be used to test whether the email's syntax is valid.

var validEmailRegEx = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*@[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i
var isEmailValid = validEmailRegEx.test("Email To Test");

Validating email is a very important point while validating an HTML form. In this page we have discussed how to validate an email using JavaScript :

An email is a string (a subset of ASCII characters) separated into two parts by @ symbol. a "personal_info" and a domain, that is personal_info@domain. The length of the personal_info part may be up to 64 characters long and domain name may be up to 253 characters. The personal_info part contains the following ASCII characters.

  1. Uppercase (A-Z) and lowercase (a-z) English letters.
  2. Digits (0-9).
  3. Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  4. Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.

The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots.

Example of valid email id

[email protected]

[email protected]

[email protected]

Example of invalid email id

mysite.ourearth.com [@ is not present]

[email protected] [ tld (Top Level domain) can not start with dot "." ]

@you.me.net [ No character before @ ]

[email protected] [ ".b" is not a valid tld ]

[email protected] [ tld can not start with dot "." ]

[email protected] [ an email should not be start with "." ]

mysite()*@gmail.com [ here the regular expression only allows character, digit, underscore, and dash ]

[email protected] [double dots are not allowed]

JavaScript code to validate an email id

function ValidateEmail(mail) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w {2, 3})+$/.test(myForm.emailAddr.value)) {
            return (true)
        }
        alert("You have entered an invalid email address!")
        return (false)
    }

Are you also validating server-side? This is very important.

Using regular expressions for e-mail isn't considered best practice since it's almost impossible to properly encapsulate all of the standards surrounding email. If you do have to use regular expressions I'll usually go down the route of something like:

^.+@.+$

which basically checks you have a value that contains an @. You would then back that up with verification by sending an e-mail to that address.

Any other kind of regex means you risk turning down completely valid e-mail addresses, other than that I agree with the answer provided by @Ben.


function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 

To validate email id in javascript above code works.


This is quite an old question so I've updated this answer to take the HTML 5 email type into account.

You don't actually need JavaScript for this at all with HTML 5; just use the email input type:

<input type="email" />
  • If you want to make it mandatory, you can add the required parameter.

  • If you want to add additional RegEx validation (limit to @foo.com email addresses for example), you can use the pattern parameter, e.g.:

    <input type="email" pattern="[email protected]" />
    

There's more information available on MozDev.


Original answer follows


First off - I'd recommend the email validator RegEx from Hexillion: http://hexillion.com/samples/

It's pretty comprehensive - :

^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$

I think you want a function in your JavaScript like:

function validateEmail(sEmail) {
  var reEmail = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/;

  if(!sEmail.match(reEmail)) {
    alert("Invalid email address");
    return false;
  }

  return true;

}

In the HTML input you need to trigger the event with an onblur - the easy way to do this is to simply add something like:

<input type="text" name="email" onblur="validateEmail(this.value);" />

Of course that's lacking some sanity checks and won't do domain verification (that has to be done server side) - but it should give you a pretty solid JS email format verifier.

Note: I tend to use the match() string method rather than the test() RegExp method but it shouldn't make any difference.


If you wish to allow accent (see RFC 5322) and allow new domain extension like .quebec. use this expression:

/\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/
  • The '\u00C0-\u017F' part is for alowing accent. We use the unicode range for that.
  • The '{2,}' simply say a minimum of 2 char for the domain extension. You can replace this by '{2,63}' if you dont like the infinitive range.

Based on this article

JsFidler

_x000D_
_x000D_
$(document).ready(function() {_x000D_
var input = $('.input_field');_x000D_
var result = $('.test_result');_x000D_
        var regExpression = /\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/;_x000D_
    _x000D_
   $('.btnTest').click(function(){_x000D_
          var isValid = regExpression.test(input.val());_x000D_
          if (isValid)_x000D_
              result.html('<span style="color:green;">This email is valid</span>');_x000D_
           else_x000D_
              result.html('<span style="color:red;">This email is not valid</span>');_x000D_
_x000D_
   });_x000D_
_x000D_
});
_x000D_
body {_x000D_
    padding: 40px;_x000D_
}_x000D_
_x000D_
label {_x000D_
    font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type=text] {_x000D_
    width: 20em_x000D_
}_x000D_
.test_result {_x000D_
  font-size:4em;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label for="search_field">Input</label>_x000D_
<input type='text' class='input_field' />_x000D_
<button type="button" class="btnTest">_x000D_
Test_x000D_
</button>_x000D_
<br/>_x000D_
<div class="test_result">_x000D_
Not Tested_x000D_
</div>
_x000D_
_x000D_
_x000D_