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


当前回答

如果你只想做的是抓住最明显的合成错误,我会做这样的事情:

^\S+@\S+$

它通常捕获了用户所犯的最明显的错误,并确保表格主要是正确的,这就是JavaScript验证的所有内容。

EDIT:我们也可以在电子邮件中查看“。

/^\S+@\S+\.\S+$/

其他回答

我正在使用 match() 来检查标准电子邮件模式,并在输入文本中添加一个类,以通知用户。

$(document).ready(函数(){ $('#submit').on('click',函数(){ var email = $('#email').val(); var pat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if (email.match(pat)){ $('#email').addClass('input-valid'); return false; } else { $('#email').addClass('input-error').val(''); return false

我稍微修改了Jaymon的答案,对于那些想要真正简单的验证的人来说:

anystring@anystring.anystring

常规表达:

/^\S+@\S+\.\S+$/

防止多种 @ 标志相匹配:

/^[^\s@]+@[^\s@]+\.[^\s@]+$/

上面的序列匹配整个序列,删除领先和 ^ 并追踪 $ 如果你想匹配在序列中的任何地方。

如果你想匹配整个字符串,你可能想先切割()字符串。

示例 JavaScript 功能:

函数验证电子邮件(电子邮件) { var re = /\S+@\S+\.\S+/; return re.test(电子邮件); } console.log(验证电子邮件(我的电子邮件是 anystring@anystring.any')); // true console.log(验证电子邮件(我的电子邮件是 anystring@anystring.any')); // false

如果你只想做的是抓住最明显的合成错误,我会做这样的事情:

^\S+@\S+$

它通常捕获了用户所犯的最明显的错误,并确保表格主要是正确的,这就是JavaScript验证的所有内容。

EDIT:我们也可以在电子邮件中查看“。

/^\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;
    }
    }

HTML5 本身有电子邮件验证,如果您的浏览器支持 HTML5,则可以使用下列代码。

<form>
  <label>Email Address
    <input type="email" placeholder="me@example.com" required>
  </label>
  <input type="submit">
</form>

JSFiddle 链接

从HTML5 spec:

有效的电子邮件地址是一条符合下一个ABNF的电子邮件生产的行,字符设置为 Unicode. 电子邮件 = 1*( atext / "." ) “@” 标签 *( "." 标签 ) 标签 = let-dig [ [ [ ldh-str ] let-dig ] ; 限于 RFC 1034 节 3.5 节 atext = < 如 RFC 5322 节 3.2.3 定义 > let-dig = < 如 RFC 1034 节 3.5 定义 > ldh-str