我想用jquery validate来检查结束日期是否大于或等于开始日期。验证结束日期大于开始日期,但不允许结束日期等于开始日期,
这是我的代码 -
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date($(params).val());
}
return isNaN(value) && isNaN($(params).val())
|| (Number(value) > Number($(params).val()));
},'Must be greater than {0}.');
jQuery("#collect_and_delivery").validate({
errorElement:'div',
rules: {
from:{
required:true
},
to:{
required:true
},
start_date:{
required:true
},
end_date:{
required:true,
greaterThan: "#start_date"
}
},
messages: {
from:"Please enter collect address",
to:"Please enter delivery address",
start_date:"Please enter shipping collect date",
end_date:
{
required:"Please enter shipping delivery date",
greaterThan:"Delivery date and Collect date should be proper"
}
}
});
答案 0 :(得分:2)
您应该在自定义方法is greater than or equal to
中使用>=
( greaterThan
)。
更改此行:
return new Date(value) > new Date($(params).val());
要:
return new Date(value) >= new Date($(params).val());
...享受
答案 1 :(得分:1)
如果您想使用简单的javascript来比较日期。这是一个;简单易行。
function compareDate() {
var str = document.getElementById("start_date").value;
var end = document.getElementById("end_date").value;
var year = str.substring(0,4);
var month = str.substring(5,7);
var date = str.substring(8,10);
var endYear = end.substring(0,4);
var endMonth = end.substring(5,7);
var endDate = end.substring(8,10);
var startDate = new Date(year, month-1, date);
var endDate = new Date(endYear, endMonth-1, endDate);
if (startDate > endDate) {
alert('start date should be less than end date');
return false;
}
else { return true; }
}