要求域名在电子邮件地址jQuery验证
问题描述:
我使用以下代码(使用 jQuery验证插件)来验证电子邮件地址:
I'm using the following code (with jQuery Validation Plugin) to validate an email address:
$(".schedule-tour-form").validate({
rules: {
Email: {
required: true,
email: true
}
},
});
<input id="email" name="Email" class="email" type="email" placeholder="name@email.com" />
问题是它仍然允许没有域后缀的电子邮件。例如它验证test @ test
如何需要域后缀?
Problem is it still allows emails without domain suffixes. For example it validates "test@test" How to I require a domain suffix?
答
官方页面的插件,甚至考虑 test @ test
as一个有效的邮件,那么我想这是打算的。您可以按照此处创建一个严格的正则表达式的新规则。
The official page of plugin, even consider test@test
as a valid mail, then I suppose that this is intended. You could create a new rules, with a strict regex pattern, as suggested here.
//custom validation rule
$.validator.addMethod("customemail",
function(value, element) {
return /^([a-zA-Z0-9_.-+])+\@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(value);
},
"Sorry, I've enabled very strict email validation"
);
然后到你的规则添加:
rules: {
email: {
required: {
depends:function(){
$(this).val($.trim($(this).val()));
return true;
}
},
customemail: true
},