Email validation using jQuery

2019-01-01 02:56发布

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

30条回答
笑指拈花
2楼-- · 2019-01-01 03:14

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>
查看更多
裙下三千臣
3楼-- · 2019-01-01 03:15
function validateEmail(emailaddress){  
   var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;  
   if(!emailReg.test(emailaddress)) {  
        alert("Please enter valid email id");
   }       
}
查看更多
零度萤火
4楼-- · 2019-01-01 03:15

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
        }
    }
});
查看更多
笑指拈花
5楼-- · 2019-01-01 03:18

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.

查看更多
爱死公子算了
6楼-- · 2019-01-01 03:19

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.

查看更多
情到深处是孤独
7楼-- · 2019-01-01 03:20

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();
}}}}}}}}}
查看更多
登录 后发表回答