如何使用JQuery来验证电子邮件地址?


当前回答

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

(incorrect code)

}

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

(right code)

}

其他回答

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

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

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

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

等等……将全部验证为“真实”电子邮件。因此,最好确保用户必须输入两次电子邮件地址,以确保他们输入相同的电子邮件地址。但要保证电子邮件地址是真实的将是非常困难的,但如果有一种方法,将是非常有趣的。但如果你只是想确保它是一封电子邮件,那就坚持使用HTML5输入。

小提琴的例子

这适用于FireFox和Chrome。它可能在ie浏览器中不起作用…但是ie浏览器很烂。所以还有…

你可以创建自己的函数

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

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

如上所述,如果你问我的话,我觉得这个已经足够好了。

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})+$/;