jQuery Validate (Date Range)

后端 未结 6 697
长发绾君心
长发绾君心 2020-12-14 03:47

Im using the jQuery validate plugin and was wondering if there was a way to validate if the date entered into a field was a date like yyyy-mm-dd AND the the date falls betwe

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 04:26

    Made a couple small corrections in Connor's code.

    The resulting working code is:

    $.validator.addMethod('daterange', function(value, element, arg) {
        if (this.optional(element) && !value) {
            return true;
        }
    
        var startDate = Date.parse(arg[0]),
            endDate = Date.parse(arg[1]),
            enteredDate = Date.parse(value);
    
        if (isNaN(enteredDate)) {
            return false;
        }
    
        return ( (isNaN(startDate) || (startDate <= enteredDate)) &&
                 (isNaN(endDate) || (enteredDate <= endDate)));
    
    
       }, $.validator.format("Please specify a date between {0} and {1}."));
    

    Then use it like this:

    $("#some_date_input").rules("add",{daterange:['01/31/2001','01/31/2020']});
    

提交回复
热议问题