375

I'm new to jQuery and was wondering how to use it to validate email addresses.

Alireza Sabahi
  • 539
  • 1
  • 9
  • 26
DuH
  • 3,767
  • 3
  • 14
  • 3
  • Before trying to "validate" an email address, you should read this: https://hackernoon.com/the-100-correct-way-to-validate-email-addresses-7c4818f24643 – Mikko Rantalainen May 29 '18 at 11:26

35 Answers35

747

You can use regular old javascript for that:

function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}
Sam Leach
  • 12,076
  • 8
  • 39
  • 71
Fabian
  • 12,999
  • 6
  • 27
  • 52
  • 67
    Yes it will, remember jQuery is still javascript :) – Fabian Mar 24 '10 at 11:03
  • 36
    Even though this regexp considers most real world addresses valid, it still has a lot of false positives and false negatives. For instance, see [examples of valid and invalid email addresses](http://en.wikipedia.org/wiki/Email_address#Valid_email_addresses) on Wikipedia. – Arseny Oct 29 '12 at 01:50
  • with this regex ... would +@-.0 be a valid email? – Benjamin Eckstein Jun 13 '13 at 14:17
  • 1
    @Umingo email@127.0.0.1 is still valid e-mail, however, it still could be written in better way. None part of domain can start with other char than [a-z0-9] (case insensitive). Also, valid e-mail (and domain) has some len limit, which is also not tested. – tomis Jul 05 '13 at 08:42
  • This would pass abc@xyz.com.aaaaaaa as a valid email but the tld should be 2-4 characters. A better suggestion is /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]){2,4}$/ But of coursr this can be further improved... – Imdad Jun 13 '14 at 05:41
  • 11
    With new top level domains becoming more common this regex may need modifying .systems and .poker etc are all valid TLDs now but would fail the regex check – Liath Sep 05 '14 at 07:35
  • 4
    Per Theo's comment on another answer, you should change `var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;` to `var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,6})+$/;` to support the newer TLD's like .museum, etc – Ira Herman Jul 11 '18 at 21:15
  • 2
    To keep up to date with the regx that will work for email addresses, you can look at https://emailregex.com/ . Currently it's ```/^(([^<>()\[\]\\.,;:\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,}))$/``` – DrCJones Sep 19 '19 at 20:49
177

jQuery Function to Validate Email

I really don’t like to use plugins, especially when my form only has one field that needs to be validated. I use this function and call it whenever I need to validate an email form field.

 function validateEmail($email) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  return emailReg.test( $email );
}

and now to use this

if( !validateEmail(emailaddress)) { /* do stuff here */ }

Cheers!

CalumMcCall
  • 1,605
  • 3
  • 21
  • 43
Manish Shrivastava
  • 26,075
  • 13
  • 88
  • 100
  • 16
    You should just return `emailReg.test($email);` – nffdiogosilva Nov 13 '13 at 14:02
  • 7
    Just FYI this returns true for a blank email address. e.g. `emailReg.text("")` `true`. I'd simply the function down to the declaration of the emailReg var then this: `return ( $email.length > 0 && emailReg.test($email))` – Diziet Jan 09 '14 at 16:06
  • 14
    The regex for checking the emailaddress validity is outdated since we now have domainname extensions with 6 characters like .museum, therefor you would want to change `var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;` to `var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,6})?$/;` – Theo Feb 21 '14 at 08:31
  • 3
    right you are @h.coates! I came to this thread hoping to find that jQuery actually had a built in email validation. Move along, these aren't the droids you are looking for... – iGanja Apr 04 '14 at 22:16
  • 3
    @Theo's point is vital, but the actual length of the TLD should be more than 6, the theoretical upper limit for the extension is 63 characters. currently the longest one is over 20 see http://data.iana.org/TLD/tlds-alpha-by-domain.txt – Jeroenv3 Jun 24 '15 at 12:24
  • It returns true for blank input. – Sandeep Patel Mar 22 '19 at 13:16
41

I would use the jQuery validation plugin for a few reasons.

You validated, ok great, now what? You need to display the error, handle erasing it when it is valid, displaying how many errors total perhaps? There are lots of things it can handle for you, no need to re-invent the wheel.

Also, another huge benefit is it's hosted on a CDN, the current version at the time of this answer can be found here: http://www.asp.net/ajaxLibrary/CDNjQueryValidate16.ashx This means faster load times for the client.

Nick Craver
  • 594,859
  • 130
  • 1,270
  • 1,139
  • 7
    Ok ... no need to reinvent the wheel. But why do I have to install dozens of KByte of Javascript for validating a field. It's like building a car factory if all you need is a new wheel :) – kraftb Feb 25 '14 at 15:49
  • 3
    @kraftb As stated in my answer, it's the handling and display around the validation, not just validating the text itself. – Nick Craver Feb 25 '14 at 16:01
  • 5
    **Thanks for this @NickCraver:** This really looks to be a "best practice" approach to the problem of handling validation for an email. This most certainly is NOT like building a factory (writing up the libs to do all the work) to get a wheel. It's like following the instructions from the factory to install the wheel on a modern vehicle (jack the car up, place the wheel - put on the lug nuts) instead of trying to figure out how to get a wagon wheel on your car. This plugin is super simple to use. To do the form validation it's literally an include, some annotations, and a single method call. – jfgrissom Jul 30 '14 at 18:30
  • 4
    Now you're reinventing the 'reinventing the wheel' metaphor! – Dom Vinyard Aug 10 '15 at 09:48
  • For people stuck working on webforms apps http://encosia.com/using-jquery-validation-with-asp-net-webforms/ – Jerreck Jan 29 '16 at 00:41
  • The simple distinctions is: Use the jQueryValidate plugin if want: (A) The full suite of validation functionality; (B) Something that will likely keep pace with standards, and browser quirks. Use the local regex function, if: (A) all you want to do is validate an email address, and don't want to down load a bulldozer to merely dig a 6" hole; (B) You don't mind keeping your own code up-to-date. – ReverseEMF Apr 03 '21 at 14:35
39

Look at http: //bassistance.de/jquery-plugins/jquery-plugin-validation/. It is nice jQuery plugin, which allow to build powerfull validation system for forms. There are some usefull samples here. So, email field validation in form will look so:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      email: true
    }
  }
});

See Email method documentation for details and samples.

Menuka Ishan
  • 3,169
  • 2
  • 42
  • 55
17
<script type="text/javascript">
    $(document).ready(function() {
      $('.form_error').hide();
      $('#submit').click(function(){
           var name = $('#name').val();
           var email = $('#email').val();
           var phone = $('#phone').val();
           var message = $('#message').val();
           if(name== ''){
              $('#name').next().show();
              return false;
            }
            if(email== ''){
               $('#email').next().show();
               return false;
            }
            if(IsEmail(email)==false){
                $('#invalid_email').show();
                return false;
            }

            if(phone== ''){
                $('#phone').next().show();
                return false;
            }
            if(message== ''){
                $('#message').next().show();
                return false;
            }
            //ajax call php page
            $.post("send.php", $("#contactform").serialize(),  function(response) {
            $('#contactform').fadeOut('slow',function(){
                $('#success').html(response);
                $('#success').fadeIn('slow');
               });
             });
             return false;
          });
      });
      function IsEmail(email) {
        var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(!regex.test(email)) {
           return false;
        }else{
           return true;
        }
      }
  </script>

<form action="" method="post" id="contactform">
                            <table class="contact-table">
                              <tr>
                                <td><label for="name">Name :</label></td>
                                <td class="name"> <input name="name" id="name" type="text" placeholder="Please enter your name" class="contact-input"><span class="form_error">Please enter your name</span></td>
                              </tr>
                              <tr>
                                <td><label for="email">Email :</label></td>
                                <td class="email"><input name="email" id="email" type="text" placeholder="Please enter your email" class="contact-input"><span class="form_error">Please enter your email</span>
                                  <span class="form_error" id="invalid_email">This email is not valid</span></td>
                              </tr>
                              <tr>
                                <td><label for="phone">Phone :</label></td>
                                <td class="phone"><input name="phone" id="phone" type="text" placeholder="Please enter your phone" class="contact-input"><span class="form_error">Please enter your phone</span></td>
                              </tr>
                              <tr>
                                <td><label for="message">Message :</label></td>
                                <td class="message"><textarea name="message" id="message" class="contact-input"></textarea><span class="form_error">Please enter your message</span></td>
                              </tr>
                              <tr>
                                <td></td>
                                <td>
                                  <input type="submit" class="contactform-buttons" id="submit"value="Send" />
                                  <input type="reset" class="contactform-buttons" id="" value="Clear" />
                                </td>
                              </tr>
                            </table>
     </form>
     <div id="success" style="color:red;"></div>
user1993920
  • 199
  • 1
  • 6
  • good example, I think adding jQuery validate for email validation would have made it much easier, also we can do HTML5 regex, check for possible ways: https://qawithexperts.com/article/jquery/email-validation-using-jquery-various-methods/288 – Vikas Lalwani Nov 02 '20 at 11:40
15

<!-- Dont forget to include the jQuery library here -->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {

    $("#validate").keyup(function(){

        var email = $("#validate").val();

        if(email != 0)
        {
            if(isValidEmailAddress(email))
            {
                $("#validEmail").css({
                    "background-image": "url('validYes.png')"
                });
            } else {
                $("#validEmail").css({
                    "background-image": "url('validNo.png')"
                });
            }
        } else {
            $("#validEmail").css({
                "background-image": "none"
            });         
        }

    });

});

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

</script>

<style>
    #validEmail
    {
        margin-top: 4px;
        margin-left: 9px;
        position: absolute;
        width: 16px;
        height: 16px;
    }

    .text
    {
        font-family: Arial, Tahoma, Helvetica;
    }
</style>

    <title>Live Email Validation with jQuery Demo</title>
</head>
<body>
    <div class="text"><h1>Reynoldsftw.com - Live Email Validation</h1><h2>Type in an email address in the box below:</h2></div>
    <div><input type="text" id="validate" width="30"><span id="validEmail"></span></div>
    <div class="text"><P>More script and css style

: www.htmldrive.net


Source:htmldrive.com

SwatiKothari
  • 351
  • 3
  • 8
15

function isValidEmailAddress(emailAddress) {
    var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
    return pattern.test(emailAddress);
};
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here (email is invalid) */ }

this was provided by user Luca Filosofi in this answer this answer

Community
  • 1
  • 1
Amila kumara
  • 419
  • 7
  • 11
  • If you using this in ASP.NET MVC Razor page, don't forget to escape the `@` character with another `@` character. Like so `@@`, otherwise you will get build error. – Rosdi Kasim Jun 13 '17 at 17:23
14

I would recommend Verimail.js, it also has a JQuery plugin.

Why? Verimail supports the following:

  • Syntax validation (according to RFC 822)
  • IANA TLD validation
  • Spelling suggestion for the most common TLDs and email domains
  • Deny temporary email account domains such as mailinator.com

So besides validation, Verimail.js also gives you suggestions. So if you type an email with the wrong TLD or domain that is very similar to a common email domain (hotmail.com, gmail.com, etc), it can detect this and suggest a correction.

Examples:

  • test@gnail.con -> Did you mean test@gmail.com?
  • test@hey.nwt -> Did you mean test@hey.net?
  • test@hottmail.com -> Did you mean test@hotmail.com?

And so on..

To use it with jQuery, just include verimail.jquery.js on your site and run the function below:

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

The message element is an element in which a message will be shown. This can be everything from "Your email is invalid" to "Did you mean ...?".

If you have a form and want to restrict it so that it cannot be submitted unless the email is valid, then you can check the status using the getVerimailStatus-function as shown below:

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid
}else{
    // Valid
}

This function returns an integer status code according to the object Comfirm.AlphaMail.Verimail.Status. But the general rule of thumb is that any codes below 0 is codes indicating errors.

Robin Orheden
  • 2,634
  • 20
  • 23
  • `.getVerimailStatus()` doesn't return numeric status codes, just a string value of `success`, `error` or possibly `pending` (didn't verify the last one). – Niko Nyman Apr 20 '14 at 20:26
12

As others have mentioned you can use a regex to check if the email address matches a pattern. But you can still have emails that match the pattern but my still bounce or be fake spam emails.

checking with a regex

var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);

checking with a real email validation API

You can use an API which will check if the email address is real and currently active.

var emailAddress = "foo@bar.com"
response = $.get("https://isitarealemail.com/api/email/validate?email=" +
    emailAddress,
    function responseHandler(data) {
        if (data.status === 'valid') {
            // the email is valid and the mail box is active
        } else {
            // the email is incorrect or unable to be tested.
        }
    })

For more see https://isitarealemail.com or blog post

Community
  • 1
  • 1
Stephen
  • 3,445
  • 4
  • 22
  • 37
11

Javascript Email Validation in MVC/ASP.NET

The problem I came across while using Fabian's answer, is implementing it in an MVC view because of the Razor @ symbol. You have to include an additional @ symbol to escape it, like so: @@

To Avoid Razor In MVC

function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

I didn't see it elsewhere on this page, so I thought it might be helpful.

EDIT

Here's a link from Microsoft describing it's usage.
I just tested the code above and got the following js:

function validateEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
  return regex.test(email);
}

Which is doing exactly what it's supposed to do.

Trevor Nestman
  • 2,032
  • 16
  • 22
  • @nbrogi What do you mean this doesn't work? I just checked this again and this produces the following js `var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;` What's happening to your code? – Trevor Nestman Feb 06 '17 at 15:45
  • Sorry, I'm not sure at the moment, I completely changed it. – nkkollaw Feb 06 '17 at 20:16
  • Please let me know when you can. If this is bad information, then I'll take it down. I try to contribute helpful information when possible and this helped me when writing a regex in an MVC view. – Trevor Nestman Feb 06 '17 at 20:20
  • Again, I'd like to know why this was downvoted. It does exactly what I'm wanting it to which is produce the `@` symbol in a regex in `.cshtml`. Normally it would try to treat everything after the `@` symbol as razor code, but the double `@@` prevents that. – Trevor Nestman Feb 07 '17 at 15:33
  • main issue i see is in the second codeblock your regex is set to a variable named regex, but second line uses a variable named re – phlare Aug 08 '18 at 20:36
  • @phlare Nice catch. Thanks. – Trevor Nestman Aug 08 '18 at 21:22
11

A very simple solution is to use html5 validation:

<form>
  <input type="email" required pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}">

  <input type="submit">
</form>

http://jsfiddle.net/du676/56/

iamse7en
  • 602
  • 7
  • 18
10

This performs a more thorough validation, for example it checks against successive dots in the username such as john..doe@example.com

function isValidEmail(email)
{
    return /^[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}$/.test(email)
        && /^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*/.test(email);
}

See validate email address using regular expression in JavaScript.

Geek
  • 403
  • 6
  • 4
  • 1
    But are successive dots actually invalid? On the contrary I think you’d be excluding valid email addresses by doing that. – icktoofay Nov 02 '14 at 19:28
8

If you have a basic form, just make the input type of email: <input type="email" required>

This will work for browsers that use HTML5 attributes and then you do not even need JS. Just using email validation even with some of the scripts above will not do much since:

some@email.com so@em.co my@fakemail.net

etc... Will all validate as "real" emails. So you would be better off ensuring that the user has to enter their email address twice to make sure that they put the same one in. But to guarantee that the email address is real would be very difficult but very interesting to see if there was a way. But if you are just making sure that it is an email, stick to the HTML5 input.

FIDDLE EXAMPLE

This works in FireFox and Chrome. It may not work in Internet Explorer... But internet explorer sucks. So then there's that...

isaac weathers
  • 1,254
  • 4
  • 24
  • 48
  • The regexp method usually prevents clearly silly emails like a@b.c (which your linked JSFiddle example allows using latest Chrome), so the HTML5 solution is clearly an inadequate solution. – SnowInferno Sep 23 '14 at 22:45
  • cool. So how about just using the pattern match like HTML5 is "supposed" to do? Why don't you try this in your chromebook: http://jsfiddle.net/du676/8/ – isaac weathers Sep 26 '14 at 04:00
7
function isValidEmail(emailText) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailText);
};

Use Like This :

if( !isValidEmail(myEmail) ) { /* do things if myEmail is valid. */ }
JayKandari
  • 1,158
  • 3
  • 14
  • 32
6
function validateEmail(emailaddress){  
   var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;  
   if(!emailReg.test(emailaddress)) {  
        alert("Please enter valid email id");
   }       
}
JAB
  • 3,008
  • 8
  • 34
  • 38
5
<script type = "text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type = "text/javascript">
    function ValidateEmail(email) {
        var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        return expr.test(email);
    };
    $("#btnValidate").live("click", function () {
        if (!ValidateEmail($("#txtEmail").val())) {
            alert("Invalid email address.");
        }
        else {
            alert("Valid email address.");
        }
    });
</script>
<input type = "text" id = "txtEmail" />
<input type = "button" id = "btnValidate" value = "Validate" />
Pritam
  • 667
  • 13
  • 28
5

Landed here.....ended up here: https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address

...which provided the following regex:

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[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])?)*$/

...which I found thanks to a note on the jQuery Validation plugin readme: https://github.com/jzaefferer/jquery-validation/blob/master/README.md#reporting-an-issue

So, the updated version of @Fabian's answer would be:

function IsEmail(email) {
  var regex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[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])?)*$/;
  return regex.test(email);
}

Hope that helps

Community
  • 1
  • 1
timborden
  • 1,450
  • 4
  • 18
  • 24
  • This one was the best answer for me - it returned true on `john..doe@example.com` but would like that to have been false – Adam Knights Jul 22 '15 at 13:56
3

use this

if ($this.hasClass('tb-email')) {
    var email = $this.val();
    var txt = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!txt.test(email)) {
        e.preventDefault();
        $this.addClass('error');
    } else {
        $this.removeClass('error');
    }
}
MKB
  • 7,276
  • 9
  • 40
  • 66
Ankit Agrawal
  • 2,337
  • 1
  • 11
  • 25
3

Bug is in Jquery Validation Validation Plugin Only validates with @ to change this

change the code to this

email: function( value, element ) {
    // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
    // Retrieved 2014-01-14
    // If you have a problem with this implementation, report a bug against the above spec
    // Or use custom methods to implement your own email validation
    return this.optional( element ) || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test( value );
}
ernd enson
  • 1,694
  • 1
  • 14
  • 28
3

For thoose who want to use a better maintainable solution than disruptive lightyear-long RegEx matches, I wrote up a few lines of code. Thoose who want to save bytes, stick to the RegEx variant :)

This restricts:

  • No @ in string
  • No dot in string
  • More than 2 dots after @
  • Bad chars in the username (before @)
  • More than 2 @ in string
  • Bad chars in domain
  • Bad chars in subdomain
  • Bad chars in TLD
  • TLD - addresses

Anyways, it's still possible to leak through, so be sure you combine this with a server-side validation + email-link verification.

Here's the JSFiddle

 //validate email

var emailInput = $("#email").val(),
    emailParts = emailInput.split('@'),
    text = 'Enter a valid e-mail address!';

//at least one @, catches error
if (emailParts[1] == null || emailParts[1] == "" || emailParts[1] == undefined) { 

    yourErrorFunc(text);

} else {

    //split domain, subdomain and tld if existent
    var emailDomainParts = emailParts[1].split('.');

    //at least one . (dot), catches error
    if (emailDomainParts[1] == null || emailDomainParts[1] == "" || emailDomainParts[1] == undefined) { 

        yourErrorFunc(text); 

     } else {

        //more than 2 . (dots) in emailParts[1]
        if (!emailDomainParts[3] == null || !emailDomainParts[3] == "" || !emailDomainParts[3] == undefined) { 

            yourErrorFunc(text); 

        } else {

            //email user
            if (/[^a-z0-9!#$%&'*+-/=?^_`{|}~]/i.test(emailParts[0])) {

               yourErrorFunc(text);

            } else {

                //double @
                if (!emailParts[2] == null || !emailParts[2] == "" || !emailParts[2] == undefined) { 

                        yourErrorFunc(text); 

                } else {

                     //domain
                     if (/[^a-z0-9-]/i.test(emailDomainParts[0])) {

                         yourErrorFunc(text); 

                     } else {

                         //check for subdomain
                         if (emailDomainParts[2] == null || emailDomainParts[2] == "" || emailDomainParts[2] == undefined) { 

                             //TLD
                             if (/[^a-z]/i.test(emailDomainParts[1])) {

                                 yourErrorFunc(text);

                              } else {

                                 yourPassedFunc(); 

                              }

                        } else {

                             //subdomain
                             if (/[^a-z0-9-]/i.test(emailDomainParts[1])) {

                                 yourErrorFunc(text); 

                             } else {

                                  //TLD
                                  if (/[^a-z]/i.test(emailDomainParts[2])) {

                                      yourErrorFunc(text); 

                                  } else {

                                      yourPassedFunc();
}}}}}}}}}
3

You can use jQuery Validation and, in a single HTML line, you can validate the email and the email validation message: type="email" required data-msg-email="Enter a valid email account!"

You can use the data-msg-email parameter to place a personalized message or otherwise do not place this parameter and the default message will be displayed: "Please enter a valid email address."

Full example:

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required data-msg-email="Enter a valid email account!">
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
<script>
$("#commentForm").validate();
</script>
J.C. Gras
  • 3,419
  • 28
  • 32
2
if($("input#email-address").getVerimailStatus() < 0) { 

(incorrect code)

}

if($("input#email-address").getVerimailStatus() == 'error') { 

(right code)

}
Code Lღver
  • 15,171
  • 16
  • 51
  • 71
Lorenzo
  • 29
  • 1
  • 10
    Can you elaborate your answer... for example you should mention that getVerimailStatus is an additional plugin. – Dave Hogan Oct 27 '12 at 09:43
2
checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );

Refernce : JQUERY UI WEBSITE

Daniel Adenew
  • 6,825
  • 6
  • 48
  • 70
2

you should see this:jquery.validate.js,add it to your project

using it like this:

<input id='email' name='email' class='required email'/>
Chuanshi Liu
  • 504
  • 1
  • 6
  • 10
2

Another simple and complete option:

<input type="text" id="Email"/>
<div id="ClasSpan"></div>   
<input id="ValidMail" type="submit"  value="Valid"/>  


function IsEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

$("#ValidMail").click(function () {
    $('span', '#ClasSpan').empty().remove();
    if (IsEmail($("#Email").val())) {
        //aqui mi sentencia        
    }
    else {
        $('#ClasSpan').append('<span>Please enter a valid email</span>');
        $('#Email').keypress(function () {
            $('span', '#itemspan').empty().remove();
        });
    }
});
Anders
  • 7,431
  • 6
  • 42
  • 76
jorcado
  • 31
  • 2
2

This question is more dificult to answer than seems at first sight. If you want to deal with emails correctly.

There were loads of people around the world looking for "the regex to rule them all" but the truth is that there are tones of email providers.

What's the problem? Well, "a_z%@gmail.com cannot exists but it may exists an address like that through another provider "a__z@provider.com.

Why? According to the RFC: https://en.wikipedia.org/wiki/Email_address#RFC_specification.

I'll take an excerpt to facilitate the lecture:

The local-part of the email address may use any of these ASCII characters:

- uppercase and lowercase Latin letters A to Z and a to z;
- digits 0 to 9;
- special characters !#$%&'*+-/=?^_`{|}~;
- dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. John..Doe@example.com is not allowed but "John..Doe"@example.com is allowed);[6]
Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.
- space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
- comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)john.smith@example.com are both equivalent to john.smith@example.com.

So, i can own an email address like that:

A__z/J0hn.sm{it!}h_comment@example.com.co

If you try this address i bet it will fail in all or the major part of regex posted all across the net. But remember this address follows the RFC rules so it's fair valid.

Imagine my frustration at not being able to register anywhere checked with those regex!!

The only one who really can validate an email address is the provider of the email address.

How to deal with, so?

It doesn't matter if a user adds a non-valid e-mail in almost all cases. You can rely on HTML 5 input type="email" that is running near to RFC, little chance to fail. HTML5 input type="email" info: https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html

For example, this is an RFC valid email:

"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com

But the html5 validation will tell you that the text before @ must not contain " or () chars for example, which is actually incorrect.

Anyway, you should do this by accepting the email address and sending an email message to that email address, with a code/link the user must visit to confirm validity.

A good practice while doing this is the "enter your e-mail again" input to avoid user typing errors. If this is not enough for you, add a pre-submit modal-window with a title "is this your current e-mail?", then the mail entered by the user inside an h2 tag, you know, to show clearly which e-mail they entered, then a "yes, submit" button.

JoelBonetR
  • 1,469
  • 1
  • 10
  • 18
1

A simplified one I've just made, does what I need it to. Have limited it to just alphanumeric, period, underscore and @.

<input onKeyUp="testEmailChars(this);"><span id="a"></span>
function testEmailChars(el){
    var email = $(el).val();
    if ( /^[a-zA-Z0-9_@.-]+$/.test(email)==true ){
        $("#a").html("valid");
    } else {
        $("#a").html("not valid");
    }
}

Made with help from others

nathan
  • 129
  • 1
  • 1
  • 10
1

This regexp prevents duplicate domain names like abc@abc.com.com.com.com, it will allow only domain two time like abc@abc.co.in. It also does not allow statring from number like 123abc@abc.com

 regexp: /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\@(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/, 

All The Best !!!!!

Brijeshkumar
  • 97
  • 1
  • 8
1

Validate email while typing, with button state handling.

$("#email").on("input", function(){
    var email = $("#email").val();
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (!filter.test(email)) {
      $(".invalid-email:empty").append("Invalid Email Address");
      $("#submit").attr("disabled", true);
    } else {
      $("#submit").attr("disabled", false);
      $(".invalid-email").empty();
    }
  });
Radovan Skendzic
  • 2,688
  • 1
  • 9
  • 20
1

if you are using jquery validation

I created a method emailCustomFormat that used regex for my custm format you can change it to meet your requirments

jQuery.validator.addMethod("emailCustomFormat", function (value, element) {
        return this.optional(element) || /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/.test(value);
    }, abp.localization.localize("Please_enter_valid_email_message"));// localized message based on current language

then you can use it like this

$("#myform").validate({
  rules: {
    field: {
      required: true,
      emailCustomFormat : true
    }
  }
});

this regex accept

abc@abc.abc, abc@abc.abcd but not this

abc@abc , abc@abc.a, abc@abc.abcde

hope this helps you

Basheer AL-MOMANI
  • 11,997
  • 8
  • 79
  • 85
1

I take this code from jqvalidate version 1.11.0 and implemented in the version 1.16.0 as aditional method. It works

            jQuery.validator.addMethod("strictemail", function(value, element) {
                    var valid = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
                    return valid;
                }, "Escribe un correo v\u00e1lido"
            );

And and in the email rule

            'correo': {
                required: 'Por favor ingresa tu correo',
                email: 'Escribe un correo v\u00e1lido',
                strictemail:'Escribe un correo v\u00e1lido'
            }
Rolly
  • 2,375
  • 1
  • 17
  • 28
  • jqvalidate changed the pattern in 1.12 based on https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address – retrovertigo Sep 29 '17 at 06:35
1

You can create your own function

function emailValidate(email){
    var check = "" + email;
    if((check.search('@')>=0)&&(check.search(/\./)>=0))
        if(check.search('@')<check.split('@')[1].search(/\./)+check.search('@')) return true;
        else return false;
    else return false;
}

alert(emailValidate('your.email@yahoo.com'));
Wahid Masud
  • 873
  • 9
  • 25
0

As mentioned above, this one is good enough if you ask me.

var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;

But if you don't want the domain ending (.com, .nu, .net etc) to contain numbers (which is my prefered choice) the edited version would be :

var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z]{2,4})+$/;
anoraq
  • 387
  • 6
  • 6
0

Use jquery.validate.js,it have Microsoft ajax CDN.

$('#form').validate({
    rules:{
        "name":{
            required:true,
            maxlength:40
        },

        "email":{
            required:true,
            email:true, //for validate email
            maxlength:100
        },

        "message":{
            required:true
        }
    }
});
Frits
  • 6,116
  • 10
  • 39
  • 50
Naveen DA
  • 3,007
  • 3
  • 32
  • 42
0
$.validator.addMethod("mymail", function(value, element) {
        return this.optional( element ) || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test( value );
}, "Enter valid email!");

This may help! a small modification to the answer by user4974898!

111
  • 1,476
  • 22
  • 34
SagitSri
  • 343
  • 4
  • 12