Javascript 电子邮件验证javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2783672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:53:58  来源:igfitidea点击:

email validation javascript

javascripthtmlvalidationemail-validation

提问by input

is this javascript function (checkValidity) correct?

这个 javascript 函数 (checkValidity) 是否正确?

function checkTextBox(textBox)
{
   if (!checkValidity(textBox.getValue()))
       displayError("Error title", "Error message", textBox);
       textBox.focus();
}

function checkValidity(e) 
{
    var email;
    email = "/^[^@]+@[^@]+.[a-z]{2,}$/i";

    if (!e.match(email)){
            return false;
    else
            return true;
    }
}

EDIT:All the answers appreciated! Thanks!

编辑:感谢所有答案!谢谢!

回答by MtnViewMark

E-mail address are defined in RFC 5322, § 3.4. The relevant non-terminal is addr-spec. The definition turns out to be somewhat squirelly, due to both the complications of domain specifications and supporting old, obsolete forms. However, you can do an over-approximation for most forms with:

电子邮件地址在RFC 5322, § 3.4中定义。相关的非终端是addr-spec。由于域规范的复杂性和支持旧的、过时的形式,该定义变得有些古怪。但是,您可以使用以下方法对大多数形式进行过度近似:

^[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+@[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+

Notice that there are a very large number of legal characters. Most reg-exs get the list wrong. Yes, all those characters are legal in an e-mail address.

请注意,有大量的合法字符。大多数正则表达式都弄错了列表。是的,所有这些字符在电子邮件地址中都是合法的。

This regex will not match some very uncommon used forms like "noodle soup @ 9"@[what the.example.com]-- which is a legal e-mail address!

这个正则表达式不会匹配一些非常不常用的形式,比如"noodle soup @ 9"@[what the.example.com]——这是一个合法的电子邮件地址!

回答by cosy

function isValidEmail($email)
{
    return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
};

if(isValidEmail("[email protected]"))
{
  echo "valid";
}
else
{
   echo "aaa";
};

回答by Sune Rasmussen

Nope, that regex is not that fit for the purpose. Have a look at thisinstead (though I can't guarantee it's validity).
Also, regarding the script itself, why are you not checking like this:

不,那个正则表达式不适合这个目的。看看这个(虽然我不能保证它的有效性)。
另外,关于脚本本身,你为什么不这样检查:

function checkEmailValidity(e) {
  return e.match("some validating regex");
}

It seems like a faster, more consise, and more readable solution.

这似乎是一个更快、更简洁、更易读的解决方案。

EDIT:
It's worth noting, that it's almost impossible to write a regex that can detect any valid email address. Therefore, you might be better off with trying to make some validation algorithm, instead of a regex, as valid email adresses may be very, very complex.

编辑:
值得注意的是,编写一个可以检测任何有效电子邮件地址的正则表达式几乎是不可能的。因此,尝试制作一些验证算法而不是正则表达式可能会更好,因为有效的电子邮件地址可能非常非常复杂。

Consider this code:

考虑这个代码:

function validateEmail(email) {
    if (typeof email != "string") return false;
    email = email.split("@");
    email[1] = email[1].split(".");
    if (
        email.length !== 2 ||
        email[1].length < 2 ||
        !email[1].hasValues(String)
    ) return false;
    return true;
}

// Checks whether each key in an array has a value, and (optionally) if they match a given contructor (object type).
// I.e.: myArray.hasValues(String) // checks whether all elements in myArray has a value, a nonempty string.
Array.prototype.hasValues = function(assumedConstructor) {
    for (var i = 0; i < this.length; i++) {
        if (!this[i]) return false;
        if (assumedConstructor && this[i].constructor != assumedConstructor) return false;
    }
    return true;
};

It works this way:

它是这样工作的:

  1. First checking if the string contains one @, and only one
  2. Checks that the part after the @has at least one .
  3. Checks that there is some characters between each of the possible .'s.
  1. 首先检查字符串是否包含一个@,并且只有一个
  2. 检查后面的部分@是否至少有一个.
  3. 检查每个可能.的之间是否有一些字符。

It will still be easy to forge a fake email address, but this way we ensure that it's at least somehowproperly formatted. The only gotcha that I can think of, is @'s inside comments, which should be perfectly legal according to the RFC's, but this code will treat it as an error.
Normal internet users, which have normal email adresses, will not fail this. So how much it actually matters is up to you to decide ;)

它仍然是容易伪造一个假的电子邮件地址,但这样一来,我们确保它至少在某种程度上正确的格式。我能想到的唯一问题是@的内部注释,根据 RFC,这应该是完全合法的,但是此代码会将其视为错误。
拥有普通电子邮件地址的普通互联网用户不会失败。所以它到底有多重要由你来决定;)

The best solution, if one is available, is to put the address into some built-in method, that somehow checks for validity by trying to use the email address.

如果可用,最好的解决方案是将地址放入某种内置方法中,该方法通过尝试使用电子邮件地址以某种方式检查有效性。

回答by Mark Byers

No. It assumes that an email address can contain only one @. I would suggest reading this article.

不可以@。它假定一个电子邮件地址只能包含一个。我建议阅读这篇文章

You probably also meant \.instead of ..

您可能还表示\.代替..

回答by Raja

Try this: I am sure it takes care of all kinds of email validation.

试试这个:我相信它会处理各种电子邮件验证。

function checkEmail(email)
{   
    if(/^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(email)) {
      return true;
    } else {
      return false;
    }
}

HTH

HTH

回答by Thom Smith

Here's a regex corresponding to the RFC, also excluding the obsolete forms. I've broken it up into components so that it will be easy to read:

这是一个对应于 RFC 的正则表达式,也不包括过时的形式。我已将其分解为多个组件,以便于阅读:

IDENT = [a-z0-9](?:[a-z0-9-]*[a-z0-9])?
TEXT = [a-z0-9!#$%&'*+/=?^_`{|}~-]+

EMAIL = TEXT(?:\.TEXT)*@IDENT(?:\.IDENT)+

(Note: case insensitive.)

(注意:不区分大小写。)

This won't match email addresses that use the quoted form before the @ or the bracketed form after it, but while those forms are valid, they're hardly ever seen nowadays outside of examples, and they significantly complicate the regex.

这不会匹配在@ 之前使用引用形式或在其之后使用方括号形式的电子邮件地址,但是虽然这些形式有效,但现在除了示例之外几乎看不到它们,并且它们使正则表达式显着复杂化。

回答by Josh Stodola

Validating an email address is very difficult. It's not even worth validating on the client-side, other than very basic checking for @and .characters.

验证电子邮件地址非常困难。除了非常基本的检查@.字符之外,它甚至不值得在客户端进行验证。

Section 3.4.1 of RFC 5322elaborates on the immense variety of legal characters, and you'll see that creating a bullet-proof regex is going to be nearly impossible.

RFC 5322 的第 3.4.1 节详细阐述了各种各样的合法字符,您将看到创建防弹正则表达式几乎是不可能的。

I ended up giving up on validating because I would get occasional complaints from users saying their crazy email address does not work. So, from now on I just attempt to send the email and hope it gets delivered. If it fails to send, then I tell the user their e-mail address is problematic.

我最终放弃了验证,因为我偶尔会收到用户的抱怨,说他们疯狂的电子邮件地址不起作用。所以,从现在开始,我只是尝试发送电子邮件并希望它能够送达。如果发送失败,我会告诉用户他们的电子邮件地址有问题。

回答by Xerri

While doing a couple of searches I came across this. Its based on RFC 2822

在进行几次搜索时,我遇到了这个。它基于 RFC 2822

http://snipplr.com/view/20981/

http://snipplr.com/view/20981/