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


当前回答

在我的情况下,我想避免 ~ 和 # 这就是为什么我使用了另一个解决方案:

function validEmail(email){
  const regex = /^((?!\.)[\w\-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/;
  return regex.test(email);
}

其他回答

使用常规表达式可能是最好的方式. 你可以在这里看到大量的测试(从<unk>取出)

const validateEmail = (email) => {
  return String(email)
    .toLowerCase()
    .match(
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    );
};

下面是接受单码的常规表达式的例子:

const re =
  /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

但是,请记住,我们不应该只依靠JavaScript验证,JavaScript可以轻松禁用,这也应该在服务器侧验证。

下面是行动中的上述例子:

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

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

您可以使用此 regex (从 w3 资源(与 W3C 无关):

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailValue)

如果您使用 Node,您可以在后端以及前端使用此功能。

我不知道其他背景语言,所以我不能对其他使用情况进行评估。

微软在 ASP.NET MVC 中提供的常规表达式是

/^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/

我在这里写的,如果它是错误的 - 尽管它一直是完美的我的需求。