我正在使用jquery validate插件驗證我的表單上的所有字段,沒有問題。jquery驗證插件 - 使用單獨表中的值驗證表單
但是,我需要驗證窗體標記外的html表中的行數。
下面是有問題的元件:
- 形式:ID = 「roadForm」
- 選擇輸入:ID = 「editRoad_ProjectClassification」
- 表:ID = 「dataExistingSegments」
我的商業規則是這樣的:
- 如果「editRoad_ProjectClassification」選擇的值等於「NO TREATMENTS」,則表「dataExistingSegments」中的行數必須等於零。
- 如果「editRoad_ProjectClassification」選擇的值不等於「NO TREATMENTS」,那麼表「dataExistingSegments」中的行數必須大於零。
我已經創建了兩個自定義規則的驗證如下:
要驗證有表中沒有行如果「editRoad_ProjectClassification」等於「無治」。
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」不等於「否治」
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" } } });
這不是工作,我認爲這是因爲「數據ExistingSegments「表格不在表格內。但由於標記和CSS的完成方式,我不能將此表放置在表單中。我怎樣才能使這個工作?