我将以下jquery验证附加到具有两个datepicker字段的表单:
$("#submitform").validate(
{
debug: true,
rules: {
summary: {
validateWidthLimits: {max: 49, min: 5}
},
description: {
validateWidthLimits: {max: 49, min: 5}
},
start_date: { //HERE**
validateDate: {field: "#end_date", when: "before"}
},
end_date: { //HERE**
validateDate: {field: "#start_date", when: "after"}
},
geocomplete: {
validateWidthLimits: {max: 500, min: 5}
}
},
submitHandler: function(event, validator) {
// submitForm();
return false;
},
invalidHandler: function(event, validator) {
setFeedback2($("#mainfbf"), "All required fields must be filled out", true);
return false;
}
});
当我使用datepicker选择日期时,例如start_date,我希望start_date检查它是否在end_date之前,反之亦然end_date。
验证功能是:
$.validator.addMethod("validateDate", function(value, element, param) {
if (!value) {
message = "*";
} else if (!value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/)) {
message = "Format dd/mm/yyyy";
}
//default to true
var fieldComparison = true;
//Validate against another date field (before:after)
if (param.field) {
var compareTo = $(param.field).val();
var compareToDate = Date.parse(compareTo,"dd/MM/yyyy");
var valueDate = Date.parse(value, "dd/MM/yyyy");
var comparisonInt = valueDate.compareTo(compareToDate);//remove line
if (param.when == "after" && ((compareToDate.compareTo(valueDate)) < 0)) {
fieldComparison = false;
message = "Start date before End date";
} else if (param.when == "before" && ((compareToDate.compareTo(valueDate)) < 0)) {
fieldComparison = false;
message = "End date before Start date";
}
}
if (value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/) && fieldComparison) {
return true;
} else {
return feedBackOverride(param);
}
},messageFunction);
现在逻辑还没有完成,但是当我从日期选择器中选择一个日期时,它已经卡住了,它根据旧值而不是新选择的值进行验证。
datepicker代码是:
$(".datepicker1").datepicker({
minDate:0,
dateFormat : 'dd/mm/yy',
changeMonth : true,
changeYear : true,
yearRange : '-0:+10'
});
任何强制验证等待该字段实际完成的想法?
答案 0 :(得分:0)
您可以拥有一个隐藏字段,可以为您验证此规则。
hiddenDate: {
required: function()
{
var MESSAGE = 'VALUES NOT ENTERED';
//if Start Date and End Date is filled then do date comparison
//otherwise return false since the fields are not filled.
if($('#start_DATE').val() && $('#end_DATE').val() )
{
/* Verify start and end dates are correctly formatted */
if(isStartDateValid && isEndDateValid)
{
var selectedStart = $('#start_DATE').val();
var selectedEnd = $('#end_DATE').val();
if(selectedStart > selectedEnd)
MESSAGE = "Start date greater than end date"
else
MESSAGE = "Start date smaller than end date"
}
}
return MESSAGE ;
}
}
我添加了消息,这些消息将为true/false
个值。