[英]Validate email address textbox using JavaScript
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;我用谷歌搜索过这个,但我得到了表单验证 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 下,但“如果电子邮件无效,则不会返回相同的页面”。
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);
}
}
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);" />
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;对于 HTML 5,您实际上根本不需要 JavaScript; just use the email input type:只需使用电子邮件输入类型:
<input type="email" />
If you want to make it mandatory, you can add the required parameter.如果您想使其成为强制性的,您可以添加所需的参数。
If you want to add additional RegEx validation (limit to @foo.com email addresses for example), you can use the pattern parameter, eg:如果您想添加额外的 RegEx 验证(例如限制为@foo.com电子邮件地址),您可以使用模式参数,例如:
<input type="email" pattern=".+@foo.com" />
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't make any difference.注意:我倾向于使用match()
字符串方法而不是test()
RegExp 方法,但它应该没有任何区别。
The result in isEmailValid
can 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");
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 有效。
Validating email is a very important point while validating an HTML form.验证电子邮件是验证 HTML 表单时非常重要的一点。 In this page we have discussed how to validate an email using JavaScript :在本页中,我们讨论了如何使用 JavaScript 验证电子邮件:
An email is a string (a subset of ASCII characters) separated into two parts by @ symbol.电子邮件是由@ 符号分隔成两部分的字符串(ASCII 字符的子集)。 a "personal_info" and a domain, that is personal_info@domain.一个“personal_info”和一个域,即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. Personal_info 部分的长度最长可达 64 个字符,域名最长可达 253 个字符。 The personal_info part contains the following ASCII characters. Personal_info 部分包含以下 ASCII 字符。
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 示例
mysite@ourearth.com mysite@ourearth.com
my.ownsite@ourearth.org my.ownsite@ourearth.org
mysite@you.me.net mysite@you.me.net
Example of invalid email id无效的电子邮件 ID 示例
mysite.ourearth.com [@ is not present] mysite.ourearth.com [@ 不存在]
mysite@.com.my [ tld (Top Level domain) can not start with dot "." mysite@.com.my [ tld(顶级域)不能以点“.”开头。 ] ]
@you.me.net [ No character before @ ] @you.me.net [@ 前没有字符]
mysite123@gmail.b [ ".b" is not a valid tld ] mysite123@gmail.b [ ".b" 不是有效的 tld ]
mysite@.org.org [ tld can not start with dot "." mysite@.org.org [ tld 不能以点“.”开头。 ] ]
.mysite@mysite.org [ an email should not be start with "." .mysite@mysite.org [ 电子邮件不应以“.”开头。 ] ]
mysite()*@gmail.com [ here the regular expression only allows character, digit, underscore, and dash ] mysite()*@gmail.com [这里的正则表达式只允许字符、数字、下划线和破折号]
mysite..1234@yahoo.com [double dots are not allowed] mysite..1234@yahoo.com [不允许使用双点]
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)
}
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 提供的答案。
If you wish to allow accent (see RFC 5322 ) and allow new domain extension like .quebec.如果您希望允许重音(请参阅RFC 5322 )并允许像 .quebec 这样的新域扩展名。 use this expression:使用这个表达式:
/\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/
$(document).ready(function() { var input = $('.input_field'); var result = $('.test_result'); var regExpression = /\\b[a-zA-Z0-9\À-\ſ._%+-]+@[a-zA-Z0-9\À-\ſ.-]+\\.[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>
<!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>
<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>
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 & pattern in在上面你可以看到两个属性required & pattern
required make sure it input block have data @time of submit &需要确保它输入块有数据@time of submit &
pattern make sure it input tag validate based in pattern(regex) @time of submit模式确保它输入标签验证基于模式(正则表达式)@提交时间
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.