jQuery验证不触发方法

时间:2016-06-07 11:28:24

标签: jquery

我已经向jQuery.validator添加了另一个方法来验证日期,但是当刷新网页时,它似乎不会执行(甚至不显示警报)。注意:“oneOfGroup”方法确实正确执行。

$.validator.addMethod("validDate",
function(value, element) { alert("Here");
// Validate date
return value.match(/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/);
},
"Please enter a date in the format dd/mm/yyyy.");

$.validator.addMethod("oneOfGroup", 
function(value, element) { 
var result = (($("input[name$='txtDateOfBirth']").val().length > 0) || ($("input[name$='txtCBHRef']").val().length > 0) || ($("input[name$='txtCardNumber']").val().length > 0) || ($("input[name$='txtNationalInsuranceNumber']").val().length > 0));   //TA 
return result;
}, 
"At Least One Required");

function customValidate() {
$("#serverForm").validate(
{
rules: {
<%=txtFirstName.UniqueID %>: { required: true }
,
<%=txtSurname.UniqueID %>: { required: true }
,
<%=txtDateOfBirth.UniqueID %>: { date: true }
,
<%=txtDateOfBirth.UniqueID %>: { validDate: true }
,
<%=txtDateOfBirth.UniqueID %>: { oneOfGroup: true }  //TA
,
<%=txtCBHRef.UniqueID %>: { oneOfGroup: true }
,
<%=txtCardNumber.UniqueID %>: { oneOfGroup: true }
,
<%=txtNationalInsuranceNumber.UniqueID %>: { oneOfGroup: true }
},
messages: {
<%=txtFirstName.UniqueID %>: { required: "Required Field" }
,
<%=txtSurname.UniqueID %>: { required: "Required Field" }
,
<%=txtDateOfBirth.UniqueID %>: {  date: "Invalid Date" }
,
<%=txtDateOfBirth.UniqueID %>: {  validDate: "Invalid Date" }
,
<%=txtDateOfBirth.UniqueID %>: {  required: "Required Field" }  //TA
,
<%=txtCBHRef.UniqueID %>: { required: "Required Field" }
,
<%=txtCardNumber.UniqueID %>: { required: "Required Field" }
,
<%=txtNationalInsuranceNumber.UniqueID %>: { required: "Required Field" }
}

});

有任何解决此问题的建议吗?

1 个答案:

答案 0 :(得分:0)

我出错的地方是为每个方法为同一个字段创建多个规则,而不是应用每个方法的单个规则。

rules: {
.....
          <%=txtDateOfBirth.UniqueID %>: { oneOfGroup: true, validDate: true }
.....
},
Messages: {
.....
<%=txtDateOfBirth.UniqueID %>: { validDate: "Invalid Date/Format (dd/mm/yyyy)", required: "Required Field" }
.....
}

全部排序。