3

我想检查结束日期是否大于或等于开始日期,使用 jquery 验证。它正在验证结束日期大于开始日期,但不允许结束日期等于开始日期,

这是我的代码 -

    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"
               }
        }                
    }); 
4

2 回答 2

2

您应该在您的自定义方法中使用is greater than or equal to( ) 。>=greaterThan

更改此行:

return new Date(value) > new Date($(params).val());

至:

return new Date(value) >= new Date($(params).val());

享受...

于 2013-04-10T05:25:19.643 回答
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; }
}
于 2014-11-21T08:41:58.147 回答