我想检查用户输入是否是JavaScript的电子邮件地址,然后将其发送到服务器或试图发送电子邮件,以防止最基本的误解。


当前回答

最好的一个 :D(RFC友好和没有错误“太复杂”) :

function    isMail(mail)
{
    pattuser = /^([A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+\.?)*[A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+$/i;
    pattdomain = /^([A-Z0-9-]+\.?)*[A-Z0-9-]+(\.[A-Z]{2,9})+$/i;

    tab = mail.split("@");
    if (tab.length != 2)
        return false;
    return (pattuser.test(tab[0]) && pattdomain.test(tab[1]));
}

其他回答

<pre>
**The personal_info part contains the following ASCII characters.
1.Uppercase (A-Z) and lowercase (a-z) English letters.
2.Digits (0-9).
3.Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
4.Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.**
</pre>
*Example of valid email id*
<pre>
yoursite@ourearth.com
my.ownsite@ourearth.org
mysite@you.me.net
xxxx@gmail.com
xxxxxx@yahoo.com
</pre>
<pre>
xxxx.ourearth.com [@ is not present] 
xxxx@.com.my [ tld (Top Level domain) can not start with dot "." ]
@you.me.net [ No character before @ ]
xxxx123@gmail.b [ ".b" is not a valid tld ]
xxxx@.org.org [ tld can not start with dot "." ]
.xxxx@mysite.org [ an email should not be start with "." ]
xxxxx()*@gmail.com [ here the regular expression only allows character, digit, underscore and dash ]
xxxx..1234@yahoo.com [double dots are not allowed
</pre>
**javascript mail code**

    function ValidateEmail(inputText)
    {
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(inputText.value.match(mailformat))
    {
    document.form1.text1.focus();
    return true;
    }
    else
    {
    alert("You have entered an invalid email address!");
    document.form1.text1.focus();
    return false;
    }
    }

在 nodeJS 中,您也可以使用验证器节点模块,并简单地使用此类

使用 npm 安装验证器安装图书馆

var validator = require('validator');

validator.isEmail('foo@bar.com'); //=> true 

只需检查输入的电子邮件地址是否有效,或者不使用 HTML。

<input type="email"/>

没有必要写一个函数来验证。

如果您正在使用 Closure 您可以使用内置的 goog.format.Email 地址类型:

http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html

例如:

goog.format.EmailAddress.isValidAddrSpec("blah@blah.com")

请注意,通过阅读来源(上面的链接),您可以看到评论表示 IDN 不受支持,并且仅旨在覆盖大多数地址:

// This is a fairly naive implementation, but it covers 99% of use cases.
// For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax
// TODO(mariakhomenko): we should also be handling i18n domain names as per
// http://en.wikipedia.org/wiki/Internationalized_domain_name
\b[a-z][\w\d_\.]+@\w+\.[a-z]{2}[a-z]?\.?[a-z]{,2}\s

它允许:

abcxyz123@qwert.com    
abc123xyz@asdf.co.in   
abc1_xyz1@gmail1.com   
abc.xyz@gmail.com.in