使用 JavaScript 验证电子邮件地址文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7635533/
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-24 02:59:53  来源:igfitidea点击:

Validate email address textbox using JavaScript

javascript

提问by Ramasani Indrashaker

I have a requirement to validate an email address entered when a user comes out from the textbox.
I have googled for this but I got form validation JScript; I don't want form validation. I want textbox validation.
I have written below JScript but "if email invalid it's not returning the same page".

我需要验证用户从文本框出来时输入的电子邮件地址。
我用谷歌搜索过这个,但我得到了表单验证 JScript;我不想要表单验证。我想要文本框验证。
我已经写在 JScript 下,但“如果电子邮件无效,则不会返回相同的页面”。

 function validate(email) {

            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            //var address = document.getElementById[email].value;
            if (reg.test(email) == false) 
            {
                alert('Invalid Email Address');
                return (false);
            }
 }

回答by Ben

Assuming your regular expression is correct:

假设您的正则表达式是正确的:

inside your script tags

在您的脚本标签内

function validateEmail(emailField){
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(emailField.value) == false) 
        {
            alert('Invalid Email Address');
            return false;
        }

        return true;

}

in your textfield:

在您的文本字段中:

<input type="text" onblur="validateEmail(this);" />

回答by CD001

This is quite an old question so I've updated this answer to take the HTML 5 email type into account.

这是一个很老的问题,所以我更新了这个答案以考虑 HTML 5 电子邮件类型。

You don't actually need JavaScript for this at all with HTML 5; just use the emailinput type:

对于 HTML 5,您实际上根本不需要 JavaScript;只需使用电子邮件输入类型:

<input type="email" />
  • If you want to make it mandatory, you can add the requiredparameter.

  • If you want to add additional RegEx validation (limit to @foo.comemail addresses for example), you can use the patternparameter, e.g.:

    <input type="email" pattern="[email protected]" />
    
  • 如果您想使其成为强制性的,您可以添加所需的参数。

  • 如果您想添加额外的 RegEx 验证(例如限制为@foo.com电子邮件地址),您可以使用模式参数,例如:

    <input type="email" pattern="[email protected]" />
    

There's more information available on MozDev.

MozDev 上提供了更多信息。


Original answer follows


原答案如下



First off - I'd recommend the email validator RegEx from Hexillion: http://hexillion.com/samples/

首先 - 我会推荐 Hexillion 的电子邮件验证器 RegEx:http://hexillion.com/samples/

It's pretty comprehensive - :

它非常全面 - :

^(?:[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$

I think you want a function in your JavaScript like:

我认为您需要在 JavaScript 中使用一个函数,例如:

function validateEmail(sEmail) {
  var reEmail = /^(?:[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/;

  if(!sEmail.match(reEmail)) {
    alert("Invalid email address");
    return false;
  }

  return true;

}

In the HTML input you need to trigger the event with an onblur - the easy way to do this is to simply add something like:

在 HTML 输入中,您需要使用 onblur 触发事件 - 执行此操作的简单方法是简单地添加如下内容:

<input type="text" name="email" onblur="validateEmail(this.value);" />

Of course that's lacking some sanity checks and won't do domain verification (that has to be done server side) - but it should give you a pretty solid JS email format verifier.

当然,这缺少一些健全性检查,并且不会进行域验证(必须在服务器端完成)-但它应该为您提供一个非常可靠的 JS 电子邮件格式验证器。

Note: I tend to use the match()string method rather than the test()RegExp method but it shouldn'tmake any difference.

注意:我倾向于使用match()string 方法而不是test()RegExp 方法,但这应该没有任何区别。

回答by Santron Manibharathi

The result in isEmailValidcan be used to test whether the email's syntax is valid.

结果isEmailValid可用于测试电子邮件的语法是否有效。

var validEmailRegEx = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*@[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i
var isEmailValid = validEmailRegEx.test("Email To Test");

回答by Sanket Patel

function validateEmail(email) { 
    var re = /^(([^<>()[\]\.,;:\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,}))$/;
    return re.test(email);
} 

To validate email id in javascript above code works.

在上面的代码中使用 javascript 验证电子邮件 ID 有效。

回答by m.edmondson

Are you also validating server-side? This is very important.

您是否也在验证服务器端?这是非常重要的。

Using regular expressions for e-mail isn't considered best practice since it's almost impossible to properly encapsulate all of the standards surrounding email. If you do have to use regular expressions I'll usually go down the route of something like:

对电子邮件使用正则表达式不被认为是最佳实践,因为几乎不可能正确封装围绕电子邮件的所有标准。如果您确实必须使用正则表达式,我通常会采用以下方式:

^.+@.+$

which basically checks you have a value that contains an @. You would then back that up with verification by sending an e-mail to that address.

它基本上检查你有一个包含@的值。然后,您将通过向该地址发送电子邮件来进行验证。

Any other kind of regex means you risk turning down completely valid e-mail addresses, other than that I agree with the answer provided by @Ben.

任何其他类型的正则表达式都意味着您可能会拒绝完全有效的电子邮件地址,但我同意@Ben 提供的答案。

回答by logesh kumar

Validating email is a very important point while validating an HTML form. In this page we have discussed how to validate an email using JavaScript :

验证电子邮件是验证 HTML 表单时非常重要的一点。在本页中,我们讨论了如何使用 JavaScript 验证电子邮件:

An email is a string (a subset of ASCII characters) separated into two parts by @ symbol. a "personal_info" and a domain, that is personal_info@domain. The length of the personal_info part may be up to 64 characters long and domain name may be up to 253 characters. The personal_info part contains the following ASCII characters.

电子邮件是由@ 符号分隔成两部分的字符串(ASCII 字符的子集)。一个“personal_info”和一个域,即personal_info@domain。Personal_info 部分的长度最长可达 64 个字符,域名最长可达 253 个字符。Personal_info 部分包含以下 ASCII 字符。

  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.
  1. 大写 (AZ) 和小写 (az) 英文字母。
  2. 数字 (0-9)。
  3. 人物 !# $ % & ' * + - / = ? ^ _ ` { | }~
  4. 特点 。(句点、点或句号),前提是它不是第一个或最后一个字符,并且不会一个接一个。

The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots.

域名 [例如 com、org、net、in、us、info] 部分包含字母、数字、连字符和点。

Example of valid email id

有效电子邮件 ID 示例

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

Example of invalid email id

无效的电子邮件 ID 示例

mysite.ourearth.com [@ is not present]

mysite.ourearth.com [@ 不存在]

[email protected] [ tld (Top Level domain) can not start with dot "." ]

[email protected] [ tld(顶级域)不能以点“.”开头。]

@you.me.net [ No character before @ ]

@you.me.net [@ 前没有字符]

[email protected] [ ".b" is not a valid tld ]

[email protected] [ ".b" 不是有效的 tld ]

[email protected] [ tld can not start with dot "." ]

[email protected] [ tld 不能以点“.”开头。]

[email protected] [ an email should not be start with "." ]

[email protected] [ 电子邮件不应以“.”开头。]

mysite()*@gmail.com [ here the regular expression only allows character, digit, underscore, and dash ]

mysite()*@gmail.com [这里的正则表达式只允许字符、数字、下划线和破折号]

[email protected] [double dots are not allowed]

[email protected] [不允许使用双点]

JavaScript code to validate an email id

用于验证电子邮件 ID 的 JavaScript 代码

function ValidateEmail(mail) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w {2, 3})+$/.test(myForm.emailAddr.value)) {
            return (true)
        }
        alert("You have entered an invalid email address!")
        return (false)
    }

https://www.w3resource.com/javascript/form/email-validation.php

https://www.w3resource.com/javascript/form/email-validation.php

回答by MaheshMore4321

You should use below regex which have tested all possible email combination

您应该使用以下已测试所有可能的电子邮件组合的正则表达式

     function validate(email) {
            var reg = "^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$";
            //var address = document.getElementById[email].value;
            if (reg.test(email) == false) 
            {
                alert('Invalid Email Address');
                return (false);
            }  
     }

Bonus tip if you're using this in Input tag than you can directly add the regex in that tag example

如果您在 Input 标签中使用它,则额外提示,您可以直接在该标签示例中添加正则表达式

<input type="text"  
       name="email" 
       class="form-control"
       placeholder="Email" 
       required 
       pattern="^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$"/>

Above you can see two attribute required& patternin

上面可以看到两个属性需要模式

requiredmake sure it input block have data @time of submit &
patternmake sure it input tag validate based in pattern(regex) @time of submit

需要确保它输入块有数据@time of submit &
pattern确保它输入标签验证基于模式(regex)@time of submit

For more info you can go throw doc

有关更多信息,您可以去 throw doc

回答by Benoit

If you wish to allow accent (see RFC 5322) and allow new domain extension like .quebec. use this expression:

如果您希望允许重音(请参阅RFC 5322)并允许像 .quebec 这样的新域扩展名。使用这个表达式:

/\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/
  • The '\u00C0-\u017F' part is for alowing accent. We use the unicode range for that.
  • The '{2,}' simply say a minimum of 2 char for the domain extension. You can replace this by '{2,63}' if you dont like the infinitive range.
  • '\u00C0-\u017F' 部分用于允许重音。我们为此使用 unicode 范围。
  • '{2,}' 只是表示域扩展名至少有 2 个字符。如果您不喜欢不定式范围,可以将其替换为 '{2,63}'。

Based on this article

基于这篇文章

JsFidler

杰斯菲德勒

$(document).ready(function() {
var input = $('.input_field');
var result = $('.test_result');
        var regExpression = /\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/;
    
   $('.btnTest').click(function(){
          var isValid = regExpression.test(input.val());
          if (isValid)
              result.html('<span style="color:green;">This email is valid</span>');
           else
              result.html('<span style="color:red;">This email is not valid</span>');

   });

});
body {
    padding: 40px;
}

label {
    font-weight: bold;
}

input[type=text] {
    width: 20em
}
.test_result {
  font-size:4em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="search_field">Input</label>
<input type='text' class='input_field' />
<button type="button" class="btnTest">
Test
</button>
<br/>
<div class="test_result">
Not Tested
</div>

回答by Keshav Gera

enter image description here

在此处输入图片说明

<!DOCTYPE html>
    <html>
    <body>

    <h2>JavaScript Email Validation</h2>

    <input id="textEmail">

    <button type="button" onclick="myFunction()">Submit</button>

    <p id="demo" style="color: red;"></p>

    <script>
    function myFunction() {
        var email;

        email = document.getElementById("textEmail").value;

            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

            if (reg.test(textEmail.value) == false) 
            {
            document.getElementById("demo").style.color = "red";
                document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
                alert('Invalid Email Address ->'+email);
                return false;
            } else{
            document.getElementById("demo").style.color = "DarkGreen";      
            document.getElementById("demo").innerHTML ="Valid Email ->"+email;
            }

       return true;
    }
    </script>

    </body>
    </html> 

回答by lokesh

<h2>JavaScript Email Validation</h2>

<input id="textEmail">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo" style="color: red;"></p>

<script>
function myFunction() {
    var email;

    email = document.getElementById("textEmail").value;

        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(textEmail.value) == false) 
        {
        document.getElementById("demo").style.color = "red";
            document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
            alert('Invalid Email Address ->'+email);
            return false;
        } else{
        document.getElementById("demo").style.color = "DarkGreen";      
        document.getElementById("demo").innerHTML ="Valid Email ->"+email;
        }

   return true;
}
</script>