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


当前回答

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

其他回答

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

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

有关详细信息和示例,请参阅电子邮件方法文档。

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

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

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

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

小提琴的例子

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

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

这个问题要比乍看之下更难回答。如果你想正确处理邮件。

世界上有很多人在寻找“统治一切的正则表达式”,但事实是,有大量的电子邮件提供商。

有什么问题吗?好吧,“a_z%@gmail.com不可能存在,但它可能通过其他提供商存在这样的地址”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

如果你尝试这个地址,我打赌它会失败的所有或regex的主要部分张贴在整个网络。但是请记住这个地址遵循RFC规则,所以它是合理有效的。

想象一下我的沮丧,不能注册任何地方检查这些正则表达式!!

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

那么如何处理呢?

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

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

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

但是html5验证会告诉你@前面的文本不能包含"或()字符,这实际上是不正确的。

无论如何,您应该通过接受电子邮件地址并向该电子邮件地址发送电子邮件消息来实现这一点,并提供用户必须访问的代码/链接以确认有效性。

这样做的一个好做法是“再次输入您的电子邮件”,以避免用户输入错误。如果这对你来说还不够,添加一个预先提交的模式窗口,标题是“这是你当前的电子邮件吗?”,然后在用户输入的邮件中添加一个h2标签,你知道,以清楚地显示他们输入的电子邮件,然后是一个“是,提交”按钮。

我使用jQuery验证插件有几个原因。

你验证了,很好,现在呢?你需要显示错误,处理擦除它时,它是有效的,显示有多少错误,也许?它可以为你处理很多事情,不需要重新发明轮子。

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