我想检查用户输入是否是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

其他回答

JavaScript 可以匹配一个常规表达式:

emailAddress.match( / some_regex /);

下面是RFC22电子邮件的常规表达式:

^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*
"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x
7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<
!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])
[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

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

<input type="email"/>

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

這些將與上使用的電子郵件(他們正確相匹配每個規則)。Gmail /^[a-z](?!\.\.)([a-z\.])){4,28}[a-z0-9]@gmail.com$/i Yahoo /^[a-z](?!\.\.)([w\.])){3,30}[w]@yahoo.com$/i Outlook/Hotmail /[a-z](?!\.\.)([w\.])){0,62}[w]@(outlook.com♰hotmail.com)$/i

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