我已设法调整jquery表单验证示例以使用我的网站,但我不知道如何确保它只是在电话号码字段中输入的数字,而只是在电子邮件字段中输入的电子邮件地址。
请有人帮忙吗?
还想知道是否有任何可以改进的东西?
<script language="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
<script>
$(function() {
$( "#quickform" ).validate({
rules: {
name: {
required: true
},
phone: {
required: true,
phonevalidation: true
},
email: {
required: true,
emailvalidation: true
},
enquiry: {
required: true
}
},
messages: {
name: {
required: "Please enter your name."
},
phone: {
required: "Please enter your phone number."
},
email: {
required: "Please enter your email address."
},
enquiry: {
required: "Please enter your enquiry."
}
},
});
$.validator.addMethod("phonevalidation",
function(value, element) {
return /^[A-Za-z\d=#$%@_ -]+$/.test(value);
},
"Please enter a valid phone number."
);
$.validator.addMethod("emailvalidation",
function(value, element) {
return /^[A-Za-z\d=#$%@_ -]+$/.test(value);
},
"Please enter a valid email address."
);
});
</script>
编辑:
示例中已有验证方法,但不接受特殊字符。我只需要了解如何将/ ^ [A-Za-z \ d =#$%@ _ - ] + $ /更改为电子邮件和号码验证。
答案 0 :(得分:4)
验证框架中已存在email
和phone
规则
<script language="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script>
$(function() {
$( "#quickform" ).validate({
rules: {
name: {
required: true
},
phone: {
required: true,
phoneUK: true //or look at the additional-methods.js to see available phone validations
},
email: {
required: true,
email: true
},
enquiry: {
required: true
}
},
messages: {
name: {
required: "Please enter your name."
},
phone: {
required: "Please enter your phone number."
},
email: {
required: "Please enter your email address."
},
enquiry: {
required: "Please enter your enquiry."
}
},
});
});
</script>
答案 1 :(得分:1)
我建议构造一个正则表达式,并将其与用户输入的内容进行匹配,并使用match()函数。
有关如何构建正确的正则表达式的更多信息(取决于您的语言环境),请转到RegExp tutorial。
答案 2 :(得分:1)
我有英国电话号码验证
jQuery.validator.addMethod('phoneUK', function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, '');
return this.optional(element) || phone_number.match(/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/);
}, 'Please specify a valid phone number');
$('#inputTelephone').rules('add', {
required: true,
phoneUK: true
});