我正在处理简单的帐单信息表单以收集信用卡信息。jQuery验证独立元素共享一个验证测试
我有两个选择输入:
<select class="form-control exp_month exp" id="expiration_month" name="expiration_month">
<select class="form-control exp_year exp" id="expiration_year" name="expiration_year">
我想有单独的“必要”的字段中的错误(即“选择月”,“选择年”),但是,我还需要有当日期比今天更早时出现共享错误,因此如果更新了任一个月或每年,并且这是较早的日期,则用户将只看到一个“选择未来日期”消息。
我玩弄了validator.addMethod(“exp”)和验证器errorPlacement,但好像每个修补程序都让我打破了别的。
编辑:
jQuery.validator.addMethod("exp", function (value, element) {
if ($('.exp_year').val() != "" && $('.exp_month').val() != "" && new Date($('.exp_year').val(), $('.exp_month').val()) < Date.now()) {
$.validator.messages.exp = "Please select a future expiration date.";
return false;
}
return true;
}, "Please select something.");
var validator = $("#new-card-form").first().validate({
rules: {
expiration_month: 'required',
expiration_year: 'required'
},
groups: {
//ExpirationDate: "expiration_month expiration_year"
},
messages: {
expiration_month: 'Please select a month.',
expiration_year: 'Please select a year.'
},
errorPlacement: function (error, element) {
if (element.hasClass("exp")) {
if ($(".exp_past").length == 0) {
error.insertAfter(".exp_month");
error.addClass("exp_past");
}
$(".exp").valid(); // used to remove error class from both dates
}
else
error.insertAfter(element);
}
});
当你的选择器瞄准一个'id'时,你不需要使用'.first()'。由于'id'对页面来说是唯一的,因此它总是首先出现。 – Sparky