我有一个运行一些验证的表单。其中一个检查是否在一个字段中加载文件,以及是否需要检查一组复选框。
我遇到的问题是我的验证仅在触发验证时才有效。 FF和Chrome都没有给我任何错误。
<form id="supplier_registration_form" method="POST">
<label class="block label">stuff:</label>
<br />
<input name="referenceEmail3" id="referenceEmail3" value="" type="text" />
<input type="file" name="file_upload1" id="file_upload1" class="fpp_textfield" value="" />
<br />
<input type="checkbox" name="agency[]" id="one" value="one">
<label class="block label">one</label>
<input type="checkbox" name="agency[]" id="two" value="two">
<label class="block label">two</label>
<input type="checkbox" name="agency[]" id="three" value="three">
<label class="block label">three</label>
<br />
<input type="submit" name="submit" id="submit" value="Submit">
</form>
$('#supplier_registration_form').validate({
onkeyup: false,
ignore: ":hidden",
rules: {
file_upload1: { required: false, accept: "|txt|doc|pdf|docx|xls|xlsx|ppt|pptx"},
'agency[]': { required : function() {
var file = document.getElementById("file_upload1").files[0];
if (file.size > 0) {
return true;
} else {
return false;
}
}
}
},
messages: {
yearEstablished: 'Please enter a year between 1850 and 2013',
file_upload1: 'Only txt, doc, xcl, xls, ppt and pdf file extensions are allowed!',
file_upload2: 'Only txt, doc, xcl, xls, ppt and pdf file extensions are allowed!',
"agency[]": 'One or more certifying agency is required'
},
onfocusout: function (element) {
if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
var currentObj = this;
var currentElement = element;
var delay = function () {
currentObj.element(currentElement);
};
setTimeout(delay, 0);
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "agency[]" )
error.insertAfter(".certifying-agency-error");
else
error.insertAfter(element);
}
});
答案 0 :(得分:1)
尝试依赖选项
jQuery(function ($) {
$('#supplier_registration_form').validate({
onkeyup: false,
ignore: ":hidden",
rules: {
file_upload1: {
required: false,
accept: "txt|doc|pdf|docx|xls|xlsx|ppt|pptx|html"
},
'agency[]': {
required: {
depends: function () {
var file = document.getElementById("file_upload1").files;
return file.length > 0
}
}
}
},
messages: {
yearEstablished: 'Please enter a year between 1850 and 2013',
file_upload1: 'Only txt, doc, xcl, xls, ppt and pdf file extensions are allowed!',
file_upload2: 'Only txt, doc, xcl, xls, ppt and pdf file extensions are allowed!',
"agency[]": 'One or more certifying agency is required'
},
onfocusout: function (element) {
if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
var currentObj = this;
var currentElement = element;
var delay = function () {
currentObj.element(currentElement);
};
setTimeout(delay, 0);
}
},
errorPlacement: function (error, element) {
if (element.attr("name") == "agency[]") {
error.insertAfter(".certifying-agency-error");
} else {
error.insertAfter(element);
}
}
});
})
演示:Fiddle