jQuery中的电子邮件验证

时间:2016-04-12 08:22:05

标签: javascript jquery validation joomla3.0 email-validation

我使用下面的代码,它工作正常请检查下面。

$(".emailValidation").change(function(){

    $('body .emailError').remove();
    var emailVal = this.value;
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if(filter.test(emailVal) === false)
    {
        $( ".emailValidation" ).after( "<div class='emailError'>You have added wrong email address.</div>" );
    }
    else 
    {
        $('.emailError').remove();
    }

});

但是,如果用户通过 email@email.com.com ,则此验证无效。

2 个答案:

答案 0 :(得分:-1)

试试这个正则表达式,它每次都有效。

  

/ ^ [! - 一个-Z0-9〜$%^&安培; _ = +} {\']!+([ - 一个-Z0-9〜$%^&安培; _ = +} {\'] +)的 @([A-Z0-9 _] [ - A-Z0-9 _] ([ - 一个-Z0-9 _] +)* (航空| ARPA | BIZ | COM |会展| EDU | GOV |资讯|国际|密|博物馆|名称|网络|组织|职业|旅游|牧高笛| [AZ] [AZ])|([0-9] {1,3} [0-9] {1,3} [0-9] {1,3} [0-9] {1,3}))(:。。[0-9] {1, 5})?$ / I

尝试使用代码段!!!

$('form input[name="email"]').keyup(function () {
    var email = $(this).val();
var re = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
if (re.test(email)) {
    $('.msg').hide();
    $('.success').show();
} else {
    $('.msg').hide();
    $('.error').show();
}

});
.msg {
    display: none;
}
.error {
    color: red;
}
.success {
    color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form method="post">
    <div>
        <label for="email" id="email-ariaLabel">Your email address:</label>
        <input id="email" name="email" type="email" class="required" title="This is a required field" /> <span class="msg error">Not a valid email address</span>
       <span class="msg success">A valid email address!</span>

    </div>
</form>

答案 1 :(得分:-2)

请尝试使用以下代码。这适用于:


    stack@overflow@gmail.com
    stack@overflow@gmail.com.com
    stackoverflow.com@gmail.com


         $(".emailValidation").change(function(){

            $('body .emailError').remove();
            var emailVal = this.value;
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (emailVal.indexOf("@") >= 0){
              var emailExt = emailVal.split('@'); 
              var extCount = (emailExt[1].match(/.com/g) || []).length;
            }        

            if(filter.test(emailVal) === false || extCount>1)
            {
                $( ".emailValidation" ).after(   "You have added wrong email address." );
                console.log("wrong email id")
            }
            else if(extCount === 1)
            {
                $('.emailError').remove();
                console.log("Email is correct");
            }
      });