如何从自定义验证方法验证日期?

时间:2016-05-16 22:50:16

标签: jquery

您好我有以下代码来验证日期范围

HTML:

   <div class="form-group">
        <label for="txtLastName">Registration Date:</label>
        <input type="date" class="form-control" id="txtRego" name="txtRego" />
    </div>

JS:

            var f = $('#f1');//this is the form

            $.validator.addMethod('dateRange', function (value, element) {

                if ((value >= '1/31/2016' && value <= '3/31/2016')) {
                    return true;
                }
                else {
                    return false;
                }
            }, 'entered date is out of range');

 f.validate({
                rules: {

                    txtRego: {
                        dateRange: true
                    }
                },
                messages: {

                    txtRego: {
                        dateRange: 'not in range'
                    }
                }
            });

但它不验证范围。为什么它不会验证日期?

1 个答案:

答案 0 :(得分:0)

试试这个

var f = $('#f1');//this is the form
var startdate = new Date('1/31/2016');
var enddate = new Date('3/31/2016');
$.validator.addMethod('dateRange', function(value, element) {
    var value = new Date( value );
    if ((value >= startdate && value <= enddate)) {
        return true;
    } else {
        return false;
    }
}, 'entered date is out of range');

f.validate({
    rules : {

        txtRego : {
            dateRange : true
        }
    },
    messages : {

        txtRego : {
            dateRange : 'not in range'
        }
    }
});