Validate that end date is greater than start date with jQuery

前端 未结 15 1680
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 13:14

How do I check/validate in jQuery whether end date [textbox] is greater than start date [textbox]?

15条回答
  •  情话喂你
    2020-11-22 13:44

    Just expanding off fusions answer. this extension method works using the jQuery validate plugin. It will validate dates and numbers

    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}.');
    

    To use it:

    $("#EndDate").rules('add', { greaterThan: "#StartDate" });
    

    or

    $("form").validate({
        rules: {
            EndDate: { greaterThan: "#StartDate" }
        }
    });
    

提交回复
热议问题