我有一个需要验证的表单,但它没有提交按钮。 为了完成验证,我按照http://docs.jquery.com/Plugins/Validation/valid
上的示例进行了操作告诉调用.valid()函数。 所以我添加了以下代码,它运行良好:
$(".getcars").click(function() {
valid = $("#form1").valid();
if(valid){
ajaxCall();
}
});
现在我想在验证字段中添加更多规则,所以我尝试了
jQuery.validator.addMethod("lettersandnumonly", function(value, element) {
return this.optional(element) || /^[0-9A-Za-z]+$/i.test(value);
}, "Letters and numbers only ");
jQuery.validator.addMethod("nowhitespace", function(value, element) {
return this.optional(element) || /^\S+$/i.test(value);
}, "No white space please");
$(".getcars").click(function() {
valid = $("#form1").valid(
{
rules: {
postal_code: {
maxlength: 6,
lettersandnumonly: true,
nowhitespace: true
}
}
});
if(valid){
ajaxCall();
}
});
但这不起作用。在添加规则时,有人能告诉我我做错了吗?
答案 0 :(得分:1)
rule
定义会在validate()
的初始调用中进行。由于valid()
仅适用于已调用validate()
的表单,我假设您在代码中有一行调用validate()
:
$("#form1").validate();
您所要做的就是将规则定义移到初始调用中:
$("#form1").validate({
rules: {
postal_code: {
maxlength: 6,
lettersandnumonly: true,
nowhitespace: true
}
}
});
...然后像你最初那样打电话给.valid()
:
$(".getcars").click(function() {
valid = $("#form1").valid();
if(valid) {
ajaxCall();
}
});