如何使用JQuery来验证电子邮件地址?
当前回答
对于那些希望使用比破坏性的长达光年的RegEx匹配更好的可维护解决方案的人,我写了几行代码。那些想要节省字节的人,坚持使用RegEx变体:)
这种限制:
字符串中没有@ 字符串中没有点 @后面超过2个点 用户名中的错误字符(@之前) 字符串中超过2个@ 域内字符错误 子域字符错误 TLD中的坏字符 TLD -地址
无论如何,仍然有可能泄露,所以一定要将此与服务器端验证+电子邮件链接验证结合起来。
这是JSFiddle
//validate email
var emailInput = $("#email").val(),
emailParts = emailInput.split('@'),
text = 'Enter a valid e-mail address!';
//at least one @, catches error
if (emailParts[1] == null || emailParts[1] == "" || emailParts[1] == undefined) {
yourErrorFunc(text);
} else {
//split domain, subdomain and tld if existent
var emailDomainParts = emailParts[1].split('.');
//at least one . (dot), catches error
if (emailDomainParts[1] == null || emailDomainParts[1] == "" || emailDomainParts[1] == undefined) {
yourErrorFunc(text);
} else {
//more than 2 . (dots) in emailParts[1]
if (!emailDomainParts[3] == null || !emailDomainParts[3] == "" || !emailDomainParts[3] == undefined) {
yourErrorFunc(text);
} else {
//email user
if (/[^a-z0-9!#$%&'*+-/=?^_`{|}~]/i.test(emailParts[0])) {
yourErrorFunc(text);
} else {
//double @
if (!emailParts[2] == null || !emailParts[2] == "" || !emailParts[2] == undefined) {
yourErrorFunc(text);
} else {
//domain
if (/[^a-z0-9-]/i.test(emailDomainParts[0])) {
yourErrorFunc(text);
} else {
//check for subdomain
if (emailDomainParts[2] == null || emailDomainParts[2] == "" || emailDomainParts[2] == undefined) {
//TLD
if (/[^a-z]/i.test(emailDomainParts[1])) {
yourErrorFunc(text);
} else {
yourPassedFunc();
}
} else {
//subdomain
if (/[^a-z0-9-]/i.test(emailDomainParts[1])) {
yourErrorFunc(text);
} else {
//TLD
if (/[^a-z]/i.test(emailDomainParts[2])) {
yourErrorFunc(text);
} else {
yourPassedFunc();
}}}}}}}}}
其他回答
<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>
function validateEmail(emailaddress){
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailaddress)) {
alert("Please enter valid email id");
}
}
你应该看到:jquery.validate.js,把它添加到你的项目
这样使用它:
<input id='email' name='email' class='required email'/>
<!-- 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
: www.htmldrive.net
来源:htmldrive.com
降落在这里……结果是这样的: https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
...它提供了以下正则表达式:
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[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])?)*$/
...这要感谢jQuery验证插件自述文件上的注释: https://github.com/jzaefferer/jquery-validation/blob/master/README.md#reporting-an-issue
所以,@Fabian的答案的更新版本是:
function IsEmail(email) {
var regex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[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])?)*$/;
return regex.test(email);
}
希望这能有所帮助
推荐文章
- 使用jQuery改变输入字段的类型
- 使用jQuery以像素为整数填充或边距值
- 检查是否选择了jQuery选项,如果没有选择默认值
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 使用jQuery滚动到一个div
- 在JS/jQuery中触发按键/按键/按键事件?
- 如何每5秒重新加载页面?
- getJSON调用中的错误处理
- 如何用jquery或javascript排序对象数组
- 使用jQuery切换输入禁用属性
- 如何知道一个字符串开始/结束在jQuery特定的字符串?
- Twitter Bootstrap vs jQuery UI?
- 如何绑定“触摸启动”和“点击”事件,但不回应两者?
- 如何使用jQuery从URL中获得锚?
- console.log(result)输出[object对象]。我如何得到result。name?