我正在使用jquery validate插件验证表单上的所有字段,没有问题。
但是,我需要根据表单标记之外的html表中的行数来验证表单。
以下是有问题的元素:
我的商业规则是这样的:
我为验证器创建了两个自定义规则,如下所示:
如果“editRoad_ProjectClassification”等于“NO TREATMENTS”,则验证表中没有行。
g$.validator.addMethod("roadWithNoTreatmentsHasNoSegments", function (value, element, params) {
var pc = g$('#editRoad_ProjectClassification').val();
var segmentCount = g$('#dataExistingSegments tbody tr').length;
if (pc == 'NO TREATMENTS' && segmentCount > 0) {
return this.optional(element) || false;
}
else {
return this.optional(element) || true;
}
}, g$.format("Must have no segments if Project Classification is 'NO TREATMENTS'")
);
如果“editRoad_ProjectClassification”不等于“NO TREATMENTS”,则验证表中至少有一行
g$.validator.addMethod("roadWithTreatmentsHasAtLeastOneSegment", function (value, element, params) {
var pc = g$('#editRoad_ProjectClassification').val();
var segmentCount = g$('#dataExistingSegments tbody tr').length;
if (pc != 'NO TREATMENTS' && pc != '' && segmentCount == 0) {
return this.optional(element) || false;
}
else {
return this.optional(element) || true;
}
}, g$.format("Must have at least one segment if Project Classification is not 'NO TREATMENTS'")
);
然后要验证表单,我有以下内容:
g$("#roadForm").validate({
errorElement: "span",
rules: {
editRoad_Jurisdiction: "required",
editRoad_TreatmentDate: {
"required": true,
date: true,
roadDateIsValidForMultiYearPlan: true
},
editRoad_ProjectClassification: "required",
editRoad_ImprovementType: "required",
editRoad_SurfaceType: "required",
editRoad_MultiYear: "required",
editRoad_LifeExpectancy: {
"required": true,
digits: true
},
editRoad_MDOTJobID: {
digits: true
},
editRoad_ProjectID: {
maxlength: 50
},
dataExistingSegments: {
"required": true,
roadWithTreatmentsHasAtLeastOneSegment: true,
roadWithNoTreatmentsHasNoSegments: true
}
},
messages: {
editRoad_Jurisdiction: "Please select an option",
editRoad_TreatmentDate: {
required: "Please select an date",
date: "Please enter a properly formatted date"
},
editRoad_ProjectClassification: "Please select an option",
editRoad_ImprovementType: "Please select an option",
editRoad_SurfaceType: "Please select an option",
editRoad_MultiYear: "Please select an option",
editRoad_LifeExpectancy: {
required: "Please enter a value",
digits: "Must be a valid number"
},
editRoad_MDOTJobID: {
digits: "Must be a valid number"
},
editRoad_ProjectID: {
maxlength: "Cannot be more than 50 characters long"
}
}
});
这不起作用,我认为这是因为“dataExistingSegments”表不在表单中。但是由于标记和css的完成方式,我无法将此表放在表单中。我怎样才能让它发挥作用?
答案 0 :(得分:1)
好吧,我想出来了,并认为我应该在这里张贴给其他可能需要这样做的人。
我在表单内部进行了文本输入并对其进行样式设置,使其看起来像一个标签,并将其禁用,以便用户无法输入。
然后我将验证规则分配给此输入,而不是表格。现在验证工作正常,错误信息正确显示。
另一件事,我尝试隐藏输入。我希望隐藏输入,但验证消息仍会显示。但显然jquery validate插件不会对表单中的任何隐藏字段应用验证。所以这没用。输入必须是可见的,这就是为什么我把它看作标签,并禁用它(像标签一样工作)。
答案 1 :(得分:0)
有一种方法可以在jquery validate plugin中为隐藏字段应用验证。
你只需要放弃,忽略:[] 或者您可以定义您不想验证的控件