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


当前回答

显然,这就是:

/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i

从 http://fightingforalostcause.net/misc/2006/compare-email-regex.php 获取于 10 月 1 日。

当然,这就是忽略国际化。

其他回答

下面是一个简单的 regex 会只是检查一个电子邮件的基本格式,例如,X@Y.C:

上一篇:S + S + S + S + S

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

一个很好的做法是验证客户端的数据,但双重检查服务器上的验证。 考虑到这一点,您可以简单地检查是否链接看起来像客户端的有效电子邮件地址,并在服务器上进行严格的检查。

下面是我使用的JavaScript功能来检查一个字符串是否看起来像一个有效的邮件地址:

function looksLikeMail(str) {
    var lastAtPos = str.lastIndexOf('@');
    var lastDotPos = str.lastIndexOf('.');
    return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
}

解释:

lastAtPos < lastDotPos: Last @ 应该是之前的最后. 因为 @ 不能是服务器名称的一部分(我知道的范围内)。 lastAtPos > 0: 应该是某些东西(电子邮件用户名)之前的最后 @. str.indexOf('@') == -1: 应该是没有 @@ 在地址. 即使 @ 出现在电子邮件用户名中的最后一个字符,它必须引用这样“ 会是 @ 和最后一个 @ 在地址。

显然,这就是:

/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i

从 http://fightingforalostcause.net/misc/2006/compare-email-regex.php 获取于 10 月 1 日。

当然,这就是忽略国际化。

你不应该使用常规表达式来验证一个输入链来检查它是否是一个电子邮件. 它太复杂,不会覆盖所有案例。

现在,因为你只能覆盖90%的案例,写下这样的东西:

function isPossiblyValidEmail(txt) {
   return txt.length > 5 && txt.indexOf('@')>0;
}

例如,‘aaa@’是有效的,但总体而言,你得到了胡萝卜,不要被带走......一个简单的90%的解决方案比一个不起作用的100%的解决方案更好。

世界需要更简单的代码。