使用jQuery进行电子邮件验证

时间:2010-03-24 10:58:34

标签: jquery validation

我是jQuery的新手,想知道如何使用它来验证电子邮件地址。

35 个答案:

答案 0 :(得分:656)

您可以使用常规的旧javascript:

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

答案 1 :(得分:155)

验证电子邮件的jQuery函数

我真的不喜欢使用插件,特别是当我的表单只有一个需要验证的字段时。我使用此功能并在需要验证电子邮件表单字段时调用它。

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

现在要使用这个

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

干杯!

答案 2 :(得分:40)

出于某些原因,我会使用jQuery validation plugin

你验证了,好的,现在怎么样?您需要显示错误,在有效时处理擦除错误,显示总共有多少错误?它可以为您处理很多事情,无需重新发明轮子。

此外,另一个巨大的好处是它托管在CDN上,当前版本在此答案可以在这里找到:http://www.asp.net/ajaxLibrary/CDNjQueryValidate16.ashx这意味着客户端的加载时间更短。

答案 3 :(得分:35)

看看http: //bassistance.de/jquery-plugins/jquery-plugin-validation/。这是一个很好的jQuery插件,它允许为表单构建强大的验证系统。 这里有一些有用的样本 。因此,表单中的电子邮件字段验证将如下所示:

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

有关详细信息和示例,请参阅Email method documentation

答案 4 :(得分: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     


来源:htmldrive.com

答案 5 :(得分:14)

我建议Verimail.js,它也有JQuery plugin

为什么呢? Verimail支持以下内容:

  • 语法验证(根据RFC 822)
  • IANA TLD验证
  • 针对最常见的TLD和电子邮件域的拼写建议
  • 拒绝临时电子邮件帐户域名,例如mailinator.com

因此除了验证,Verimail.js还会为您提供建议。因此,如果您输入的电子邮件错误的TLD或域名与普通电子邮件域(hotmail.com,gmail.com等)非常相似,则可以检测到并建议更正。

示例:

  • test@gnail.con - &gt;你的意思是测试@ gmail.com
  • test@hey.nwt - &gt;你的意思是测试@嘿。 net
  • test@hottmail.com - &gt;你的意思是测试@ hotmail.com

等等..

要将其与jQuery一起使用,只需在您的网站上添加verimail.jquery.js并运行以下功能:

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

message元素是一个显示消息的元素。这可以是从“您的电子邮件无效”到“您的意思是......?”的所有内容。

如果你有一个表格,并希望限制它,除非电子邮件有效,否则无法提交,你可以使用getVerimailStatus函数检查状态,如下所示:

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

此函数根据Comfirm.AlphaMail.Verimail.Status对象返回整数状态代码。但一般的经验法则是,任何低于0的代码都是表示错误的代码。

答案 6 :(得分:14)

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

答案 7 :(得分:14)

&#13;
&#13;
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);
};
&#13;
&#13;
&#13;

if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here (email is invalid) */ }

这是由用户Luca Filosofi在此回复this answer

中提供的

答案 8 :(得分:10)

一个非常简单的解决方案是使用html5验证:

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

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

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

答案 9 :(得分:9)

这会执行更彻底的验证,例如它会检查用户名中的连续点,例如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);
}

请参阅validate email address using regular expression in JavaScript

答案 10 :(得分:8)

如果您有基本表单,只需输入电子邮件类型:     <input type="email" required>

这适用于使用HTML5属性的浏览器,然后您甚至不需要JS。即使使用上面的一些脚本,只是使用电子邮件验证也不会做太多事情:

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

等...将全部验证为“真实”电子邮件。因此,最好确保用户必须输入两次电子邮件地址,以确保他们将相同的电子邮件地址放入其中。但是为了保证电子邮件地址是真实的,这将是非常困难的,但是看看是否有办法。但如果您只是确保它是一封电子邮件,请坚持使用HTML5输入。

FIDDLE EXAMPLE

这适用于FireFox和Chrome。它可能无法在Internet Explorer中工作......但是Internet Explorer很糟糕。那就是......

答案 11 :(得分: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);
};

使用像这样:

if( !isValidEmail(myEmail) ) { /* do things if myEmail is valid. */ }

答案 12 :(得分:6)

MVC / ASP.NET中的Javascript电子邮件验证

我在使用Fabian的答案时遇到的问题是因为Razor @符号而在MVC视图中实现它。您必须添加一个额外的@符号才能将其转义,例如:@@

在MVC中避免剃刀

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

我在本页的其他地方没有看到它,所以我认为它可能会有所帮助。

修改

这是来自Microsoft的link,描述了它的用法。
我刚刚测试了上面的代码,得到了以下js:

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

这正是它应该做的事情。

答案 13 :(得分:6)

function validateEmail(emailaddress){  
   var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;  
   if(!emailReg.test(emailaddress)) {  
        alert("Please enter valid email id");
   }       
}

答案 14 :(得分: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" />

答案 15 :(得分:4)

登陆这里......最终来到这里: https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address

...提供了以下正则表达式:

/^[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])?)*$/

...我发现感谢有关jQuery Validation插件自述文件的说明: https://github.com/jzaefferer/jquery-validation/blob/master/README.md#reporting-an-issue

因此,@Fabian answer的更新版本为:

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);
}

希望有所帮助

答案 16 :(得分:3)

使用此

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');
    }
}

答案 17 :(得分:3)

对于想要使用更好的可维护解决方案而不是破坏性的光年长RegEx匹配的thoose,我写了几行代码。想要保存字节的人,坚持使用RegEx变体:)

这限制了:

  • 字符串中没有@
  • 字符串中没有点
  • @
  • 后超过2个点
  • 用户名中的错误字符(在@之前)
  • 字符串
  • 中超过2 @
  • 域名中的错误字符
  • 子域名中的坏字符
  • TLD中的坏人
  • TLD - 地址

无论如何,它仍然可能泄漏,因此请务必将其与服务器端验证+电子邮件链接验证相结合。

以下是 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();
}}}}}}}}}

答案 18 :(得分:2)

您应该看到:jquery.validate.js,将其添加到您的项目中

像这样使用它:

<input id='email' name='email' class='required email'/>

答案 19 :(得分:2)

另一个简单而完整的选项:

<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();
        });
    }
});

答案 20 :(得分:2)

错误在Jquery验证验证插件中仅使用@进行验证以更改此

将代码更改为此

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 );
}

答案 21 :(得分: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" );

参考:JQUERY UI网站

答案 22 :(得分:1)

我刚刚制作的一个简化的,做我需要的。 仅限于字母数字,句号,下划线和@。

<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");
    }
}

在其他人的帮助下制作

答案 23 :(得分:1)

此regexp可防止重复的域名,如abc@abc.com.com.com.com,它只允许域名两次,如abc@abc.co.in。它也不允许来自123abc@abc.com等数字的statring

 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)?$/, 

所有最好!!!!!

答案 24 :(得分:1)

在键入时验证电子邮件,使用按钮状态处理。

$("#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();
    }
  });

答案 25 :(得分:1)

if($("input#email-address").getVerimailStatus() < 0) { 

(incorrect code)

}

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

(right code)

}

答案 26 :(得分:1)

您可以使用jQuery Validation,并在单个HTML行中验证电子邮件和电子邮件验证消息:type="email" required data-msg-email="Enter a valid email account!"

您可以使用 data-msg-email 参数发出个性化消息,或者不放置此参数,并显示默认消息:&#34;请输入有效的电子邮件地址&#34;

完整示例:

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

答案 27 :(得分:1)

您可以创建自己的功能

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'));

答案 28 :(得分:1)

这个问题比初看起来更难以回答。如果您想正确处理电子邮件。

世界各地都有很多人正在寻找&#34;正则规则来统治他们所有&#34;但事实是,有电子邮件提供商的口气。

问题是什么?好吧,&#34; a_z%@gmail.com不存在,但它可能存在这样的地址,通过另一个提供商&#34; a__z@provider.com。

为什么呢? 根据RFC: https://en.wikipedia.org/wiki/Email_address#RFC_specification

我将摘录一下以方便讲座:

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.

所以,我可以拥有这样的电子邮件地址:

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

如果你试试这个地址,我敢打赌它会全部失败,或者正则表达式的主要部分都在网上发布。但请记住,此地址遵循RFC规则,因此它是公平有效的。

想象一下,我无法注册那些用正则表达式检查过的任何地方,我感到很沮丧!!

真正可以验证电子邮件地址的唯一人是电子邮件地址的提供者。

如何处理,所以?

如果用户几乎在所有情况下都添加了无效的电子邮件,则无关紧要。您可以依赖HTML 5输入类型=&#34;电子邮件&#34;正在运行接近到RFC,几乎没有失败的机会。 HTML5输入类型=&#34;电子邮件&#34;信息:https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html

例如,这是一封RFC有效的电子邮件:

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

但是html5验证会告诉你@之前的文字不能包含&#34;或()chars例如,实际上是不正确的。

无论如何,您应该接受电子邮件地址并向该电子邮件地址发送电子邮件,并使用用户必须访问的代码/链接以确认其有效性。

这样做的好习惯是&#34;再次输入您的电子邮件&#34;输入以避免用户输入错误。如果这还不够,请添加一个标题为#34的预提交模式窗口;这是您当前的电子邮件吗?&#34;,然后用户在h2标签内输入的邮件,你知道,为了清楚地显示他们输入了哪些电子邮件,然后是&#34;是,提交&#34;按钮。

答案 29 :(得分:0)

使用jquery.validate.js,它有Microsoft ajax CDN。

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

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

        "message":{
            required:true
        }
    }
});

答案 30 :(得分:0)

如果您使用jquery validation

我创建了一个方法emailCustomFormat,使用regex作为我的custm格式,您可以更改它以满足您的要求

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

那么你可以像这样使用它

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

这个正则表达式接受

abc@abc.abcabc@abc.abcd 但不是这个

abc@abcabc@abc.aabc@abc.abcde

希望这可以帮助你

答案 31 :(得分:0)

如上所述,如果你问我,这个就足够了。

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

但如果您不希望域名结尾(.com,.nu,.net等)包含数字(这是我的首选),编辑后的版本将是:

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

答案 32 :(得分:0)

我从jqvalidate版本1.11.0获取此代码,并在版本1.16.0中实现为aditional方法。它的工作原理

            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"
            );

并且在电子邮件规则

            'correo': {
                required: 'Por favor ingresa tu correo',
                email: 'Escribe un correo v\u00e1lido',
                strictemail:'Escribe un correo v\u00e1lido'
            }

答案 33 :(得分: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! small modification to the answer "user4974898"!

答案 34 :(得分:0)

就像其他人提到的那样,您可以使用正则表达式检查电子邮件地址是否与模式匹配。但是您仍然可以收到与模式匹配的电子邮件,但是我仍然会退回或成为伪造的垃圾邮件。

使用正则表达式检查

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

使用真实的电子邮件验证API进行检查

您可以使用API​​来检查电子邮件地址是否真实且当前处于活动状态。

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.
        }
    })

有关更多信息,请参见https://isitarealemail.comblog post

相关问题