下面是我为验证简单表单而编写的函数。您会看到三个日期字段:cadDocDate
(必填),cadRecDate
(可选),occyDate
(可选),每个字段使用自定义规则camsDate
。如果日期不是MM / DD / YYYY格式,则会显示该规则的验证消息。
问题是cadDocDate
的日期验证文本始终被必需的验证文本覆盖。有没有办法以 的方式编写它,如果cadDocDate
为空,必需的验证文本显示,否则显示日期验证文本
addValidation: function (parent, el) {
$.validator.addMethod(
"camsDate",
function(value, element) {
return this.optional(element) || value.match(/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/);
},
"Dates must be entered in the format MM/DD/YYYY."
);
$(el).validate({
errorClass: "validation-error",
ignore: [],
rules: {
fileType: "required",
fileSubType: "required",
fileTitle: "required",
cadDocDate: {
camsDate: true,
required: true
},
cadRecDate: {
camsDate: true
},
cadDiscipline: "required",
phoCompass: "required",
occyDate: {
camsDate: true
},
},
messages: {
fileType: "File Type is a required field.",
fileSubType: "Sub Type is a required field.",
fileTitle: "Title is a required field.",
cadDocDate: "Document Date is a required field.",
cadDiscipline: "Discipline is a required field.",
phoCompass: "Compass direction is a required field."
},
onkeyup: function (element) {
$(element).valid();
fileCenter.ui.functionality.updateErrorCount(parent);
}
});
},
答案 0 :(得分:1)
是的,这是可能的。它目前的行为方式是因为您只为cadDocDate字段定义了一个自定义消息。因此,无论调用何种验证,都将返回您定义的单个消息。要更正此问题,您应该为特定验证类型定义自定义消息。例如,
messages: {
fileType: "File Type is a required field.",
fileSubType: "Sub Type is a required field.",
fileTitle: "Title is a required field.",
cadDocDate: {
required: "Document Date is a required field."
}
}
由于本节定义了自定义消息,因此只要您不指定文本,就会使用验证方法中定义的默认消息。
查看文档以获取更多详细信息 - http://jqueryvalidation.org/validate/
查看此笔以获得简化示例 - http://codepen.io/anon/pen/vEjovP