使用 jQuery 进行电子邮件验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2507030/
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
Email validation using jQuery
提问by DuH
I'm new to jQuery and was wondering how to use it to validate email addresses.
我是 jQuery 的新手,想知道如何使用它来验证电子邮件地址。
回答by Fabian
You can use regular old javascript for that:
您可以为此使用常规的旧 javascript:
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
回答by Manish Shrivastava
jQuery Function to Validate Email
用于验证电子邮件的 jQuery 函数
I really don't like to use plugins, especially when my form only has one field that needs to be validated. I use this function and call it whenever I need to validate an email form field.
我真的不喜欢使用插件,尤其是当我的表单只有一个需要验证的字段时。我使用此函数并在需要验证电子邮件表单字段时调用它。
function validateEmail($email) {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test( $email );
}
and now to use this
现在使用这个
if( !validateEmail(emailaddress)) { /* do stuff here */ }
Cheers!
干杯!
回答by Nick Craver
I would use the jQuery validation pluginfor a few reasons.
出于几个原因,我会使用jQuery 验证插件。
You validated, ok great, now what? You need to display the error, handle erasing it when it is valid, displaying how many errors total perhaps? There are lots of things it can handle for you, no need to re-invent the wheel.
你验证了,很好,现在呢?您需要显示错误,在它有效时处理擦除它,显示总共有多少错误?它可以为您处理很多事情,无需重新发明轮子。
Also, another huge benefit is it's hosted on a CDN, the current version at the time of this answercan be found here: http://www.asp.net/ajaxLibrary/CDNjQueryValidate16.ashxThis means faster load times for the client.
此外,另一个巨大的好处是它托管在 CDN 上,可以在此处找到此答案时的当前版本:http: //www.asp.net/ajaxLibrary/CDNjQueryValidate16.ashx这意味着客户端的加载时间更快。
回答by Andrew Bashtannik
Look at http: //bassistance.de/jquery-plugins/jquery-plugin-validation/. It is nice jQuery plugin, which allow to build powerfull validation system for forms.
There are some usefull samples here. So, email field validation in form will look so:
查看http://bassistance.de/jquery-plugins/jquery-plugin-validation/。这是一个很好的 jQuery 插件,它允许为表单构建强大的验证系统。有一些有用的样品在这里。因此,表单中的电子邮件字段验证将如下所示:
$("#myform").validate({
rules: {
field: {
required: true,
email: true
}
}
});
See Email method documentationfor details and samples.
有关详细信息和示例,请参阅电子邮件方法文档。
回答by user1993920
<script type="text/javascript">
$(document).ready(function() {
$('.form_error').hide();
$('#submit').click(function(){
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var message = $('#message').val();
if(name== ''){
$('#name').next().show();
return false;
}
if(email== ''){
$('#email').next().show();
return false;
}
if(IsEmail(email)==false){
$('#invalid_email').show();
return false;
}
if(phone== ''){
$('#phone').next().show();
return false;
}
if(message== ''){
$('#message').next().show();
return false;
}
//ajax call php page
$.post("send.php", $("#contactform").serialize(), function(response) {
$('#contactform').fadeOut('slow',function(){
$('#success').html(response);
$('#success').fadeIn('slow');
});
});
return false;
});
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
}else{
return true;
}
}
</script>
<form action="" method="post" id="contactform">
<table class="contact-table">
<tr>
<td><label for="name">Name :</label></td>
<td class="name"> <input name="name" id="name" type="text" placeholder="Please enter your name" class="contact-input"><span class="form_error">Please enter your name</span></td>
</tr>
<tr>
<td><label for="email">Email :</label></td>
<td class="email"><input name="email" id="email" type="text" placeholder="Please enter your email" class="contact-input"><span class="form_error">Please enter your email</span>
<span class="form_error" id="invalid_email">This email is not valid</span></td>
</tr>
<tr>
<td><label for="phone">Phone :</label></td>
<td class="phone"><input name="phone" id="phone" type="text" placeholder="Please enter your phone" class="contact-input"><span class="form_error">Please enter your phone</span></td>
</tr>
<tr>
<td><label for="message">Message :</label></td>
<td class="message"><textarea name="message" id="message" class="contact-input"></textarea><span class="form_error">Please enter your message</span></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" class="contactform-buttons" id="submit"value="Send" />
<input type="reset" class="contactform-buttons" id="" value="Clear" />
</td>
</tr>
</table>
</form>
<div id="success" style="color:red;"></div>
回答by SwatiKothari
<!-- Dont forget to include the jQuery library here -->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#validate").keyup(function(){
var email = $("#validate").val();
if(email != 0)
{
if(isValidEmailAddress(email))
{
$("#validEmail").css({
"background-image": "url('validYes.png')"
});
} else {
$("#validEmail").css({
"background-image": "url('validNo.png')"
});
}
} else {
$("#validEmail").css({
"background-image": "none"
});
}
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
</script>
<style>
#validEmail
{
margin-top: 4px;
margin-left: 9px;
position: absolute;
width: 16px;
height: 16px;
}
.text
{
font-family: Arial, Tahoma, Helvetica;
}
</style>
<title>Live Email Validation with jQuery Demo</title>
</head>
<body>
<div class="text"><h1>Reynoldsftw.com - Live Email Validation</h1><h2>Type in an email address in the box below:</h2></div>
<div><input type="text" id="validate" width="30"><span id="validEmail"></span></div>
<div class="text"><P>More script and css style
Source:htmldrive.com
来源:htmldrive.com
回答by Robin Orheden
I would recommend Verimail.js, it also has a JQuery plugin.
我会推荐Verimail.js,它还有一个JQuery 插件。
Why? Verimail supports the following:
为什么?Verimail 支持以下内容:
- Syntax validation (according to RFC 822)
- IANA TLD validation
- Spelling suggestion for the most common TLDs and email domains
- Deny temporary email account domains such as mailinator.com
- 语法验证(根据 RFC 822)
- IANA TLD 验证
- 最常见的 TLD 和电子邮件域的拼写建议
- 拒绝临时电子邮件帐户域,例如 mailinator.com
So besides validation, Verimail.js also gives you suggestions. So if you type an email with the wrong TLD or domain that is very similar to a common email domain (hotmail.com, gmail.com, etc), it can detect this and suggest a correction.
所以除了验证,Verimail.js 也给你建议。因此,如果您使用错误的 TLD 或与常见电子邮件域(hotmail.com、gmail.com 等)非常相似的域键入电子邮件,它可以检测到这一点并提出更正建议。
Examples:
例子:
- [email protected] -> Did you mean test@gmail.com?
- [email protected] -> Did you mean test@hey.net?
- [email protected] -> Did you mean test@hotmail.com?
- [email protected] -> 你是说 test@ gmail.com吗?
- [email protected] -> 你的意思是 test@hey。净?
- [email protected] -> 你是说 test@ hotmail.com吗?
And so on..
等等..
To use it with jQuery, just include verimail.jquery.json your site and run the function below:
要将它与 jQuery 一起使用,只需在您的站点上包含verimail.jquery.js并运行以下函数:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
The message element is an element in which a message will be shown. This can be everything from "Your email is invalid" to "Did you mean ...?".
消息元素是将在其中显示消息的元素。这可以是从“您的电子邮件无效”到“您的意思是......?”的所有内容。
If you have a form and want to restrict it so that it cannot be submitted unless the email is valid, then you can check the status using the getVerimailStatus-function as shown below:
如果您有一个表单并希望对其进行限制,以便在电子邮件有效之前无法提交它,那么您可以使用 getVerimailStatus 函数检查状态,如下所示:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid
}else{
// Valid
}
This function returns an integer status code according to the object Comfirm.AlphaMail.Verimail.Status. But the general rule of thumb is that any codes below 0 is codes indicating errors.
该函数根据对象 Comfirm.AlphaMail.Verimail.Status 返回一个整数状态代码。但一般的经验法则是,任何低于 0 的代码都是指示错误的代码。
回答by Amila kumara
- http://so.devilmaycode.it/jquery-validate-e-mail-address-regex/
- using new regex
- added support for Address tags (+ sign)
- http://so.devilmaycode.it/jquery-validate-e-mail-address-regex/
- 使用新的正则表达式
- 添加了对地址标签的支持(+ 符号)
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
};
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here (email is invalid) */ }
this was provided by user Luca Filosofiin this answer this answer
这是由用户Luca Filosofi在这个答案中提供的这个答案
回答by iamse7en
A very simple solution is to use html5 validation:
一个非常简单的解决方案是使用 html5 验证:
<form>
<input type="email" required pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}">
<input type="submit">
</form>
回答by Geek
This performs a more thorough validation, for example it checks against successive dots in the username such as [email protected]
这将执行更彻底的验证,例如它检查用户名中的连续点,例如 [email protected]
function isValidEmail(email)
{
return /^[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}$/.test(email)
&& /^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*/.test(email);
}
See validate email address using regular expression in JavaScript.