我目前有一个表单,我正在使用jQuery验证器插件进行验证。在表单中,我有一个字段,根据输入的另一个字段,是否需要。jQuery验证不正确
<select name="supportiveServices" id="supportiveServices" style="float: left; margin-left: 20px; width: 30%;">
<option value="">Select One</option>
<option value="Accepted">Accepted</option>
<option value="Declined">Declined</option>
</select>
<input name= "serviceStartDate" id= "serviceStartDate" type="date" style="width: 50%;"></input>
jQuery的
serviceStartDate: {
required: function(element) {
if($("#supportiveServices").val() == 'Accepted') {
return true;
}
else {
return false;
}
},
},
这种依赖性要求似乎很好地工作,但我一直运行到的问题是我我需要的日期也有效。我已经添加了一个方法来确保日期有效。
jQuery.validator.addMethod("DateFormat",
function(value, element) {
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy";
);
我是新来这个插件,但我曾尝试以下两种解决方案,它们都返回true,需要输入:
创建,基本上返回true的函数,如果日期是空的如果不是,则为false。
serviceStartDate: { required: function(element) { if($("#supportiveServices").val() == 'Accepted') { return true; } else { return false; } }, DateFormat: function(element) { if($("#serviceStartDate").val() != 0 || $("#serviceStartDate").val() != null || $("#serviceStartDate").val() != undefined || $("#serviceStartDate").val() != '') { return true; } else { return false; } } },
创建一个单独的方法。
jQuery.validator.addMethod("DateFormatSupport", function(value, element) { if ($("#serviceStartDate") == 0) { return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/); } }, "Please enter a date in the format dd/mm/yyyy"//removed ; );
,并调用它。
serviceStartDate: {
required: function(element) {
if($("#supportiveServices").val() == 'Accepted') {
return true;
}
else {
return false;
}
},
DateFormatSupport: true
}
},
基本上,我需要验证,以确保如果客户不选择“接受”的支持性服务,那么serviceStartDate可选配。如果选择“接受”支持服务,则需要填写serviceStartDate并且日期也需要有效。作为预防措施,我想如果他们在serviceStartDate中填写任何内容(无论是否为可选)作为日期 - 这将发送到数据库,因此它必须为空或日期。
有什么建议吗?
您是否尝试过'那已经内置到插件date'规则? – Sparky