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


当前回答

这里的大多数答案不友好,这是一个混乱! 其中一些也过时了! 花了很多时间后,我决定使用一个名为电子邮件验证器的外部图书馆,通过 npm 轻松安装,例如,并在自己的项目中进口/要求:

https://www.npmjs.com/包装/电子邮件验证器

//NodeJs
const validator = require("email-validator");
validator.validate("test@email.com"); // true

//TypeScript/JavaScript
import * as EmailValidator from 'email-validator';
EmailValidator.validate("test@email.com"); // true

其他回答

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

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

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

有一些复杂的RegEx写在这里,这也工作。

我试过这个,它也工作了:

[a-zA-Z0-9._]+[@]+[a-zA-Z0-9]+[.]+[a-zA-Z]{2,6}

请点击此处: http://www.regextester.com/?fam=97334

希望这能帮助。

<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 会只是检查一个电子邮件的基本格式,例如,X@Y.C:

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

在现代浏览器中,您可以使用纯粹的JavaScript和DOM创建 @Sushil的答案:

function validateEmail(value) {
  var input = document.createElement('input');

  input.type = 'email';
  input.required = true;
  input.value = value;

  return typeof input.checkValidity === 'function' ? input.checkValidity() : /\S+@\S+\.\S+/.test(value);
}

我把一个例子聚集在一个字符串 http://jsfiddle.net/boldewyn/2b6d5/. 结合功能检测和Squirtle的答案的字符串验证,它释放了你从常规的表达屠杀,并不会在旧的浏览器上跳舞。