jQuery 验证(日期范围)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3761185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:03:01  来源:igfitidea点击:

jQuery Validate (Date Range)

jqueryjquery-pluginsjquery-validate

提问by Shane

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 between Nov 29 2010 - Dec 15 2010

我正在使用 jQuery 验证插件,想知道是否有办法验证输入到字段中的日期是否是 yyyy-mm-dd 之类的日期,并且该日期介于 2010 年 11 月 29 日至 2010 年 12 月 15 日之间

Im pretty new to jQuery so if there is an answer please dumb up the answer as much as possible so i can get through it. Thanks a lot for any/all suggestions

我对 jQuery 还很陌生,所以如果有答案,请尽可能地把答案弄糊涂,这样我就可以通过它。非常感谢任何/所有建议

回答by Connor M

If you want a reusable function, you might extend Emily and lonesomeday's answers to allow an argument to be provided:

如果你想要一个可重用的函数,你可以扩展 Emily 和 lonesomeday 的答案以允许提供一个参数:

$.validator.addMethod('daterange', function(value, element, arg) {
     // Same as above

     var startDate = Date.parse(arg[0]),
         endDate = Date.parse(arg[1]),
         enteredDate = Date.parse(value);       
     // Same as below

 }, $.validator.format("Please specify a date between {0} and {1}."))

See the sourceof the jQuery validation rangemethod for an example.

有关示例,请参阅jQuery 验证范围方法的来源

回答by lonesomeday

I've never used the validation plugin, but a look through the API suggests that something like this might work:

我从来没有使用过验证插件,但通过 API 看一下,这样的事情可能会奏效:

$.validator.addMethod('daterange', function(value, element) {
    if (this.optional(element)) {
        return true;
    }

    var startDate = Date.parse('2010-11-29'),
        endDate = Date.parse('2010-12-15'),
        enteredDate = Date.parse(value);

    if (isNan(enteredDate)) {
        return false;
    }

    return ((startDate <= enteredDate) && (enteredDate <= endDate));
});

You would then, I think, need to add the daterangeclass the the appropriate element.

然后,我认为,您需要为daterange类添加适当的元素。

回答by Emily

lonesomeday's answer is pretty close, with a few tweaks. I would end the code as follows:

lonesomeday 的答案非常接近,有一些调整。我会按如下方式结束代码:

    if(isNaN(enteredDate)) return false;

    return ((startDate <= enteredDate) && (enteredDate <= endDate));
}, "Please specify a date between 2010-11-29 and 2010-12-15");

This fixes the isNaN function, and also provides an error message to your users so they know what you're looking for.

这修复了 isNaN 函数,并且还向您的用户提供了一条错误消息,以便他们知道您在寻找什么。

回答by Taras Bilinsky

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

回答by Alexander

Hold your horses, guys! :)

抓住你的马,伙计们!:)

Do not forget, that Date.parse cannot work properly with different locales, it only parses properly specific date format.

不要忘记, Date.parse 不能在不同的语言环境下正常工作,它只能正确解析特定的日期格式。

If you use various date formats (culture-specific) - it's better to stick to jquery datepicker date handling.

如果您使用各种日期格式(特定于文化) - 最好坚持使用 jquery datepicker 日期处理。

So, supposing you've loaded correct culture-specific jquery datepicker object (for instance, jquery.ui.datepicker-nb-NO.js, where date format is DD.MM.yyyy and is not parsed by Date.parse) and initialized it, proper approach is:

因此,假设您已加载正确的特定于文化的 jquery datepicker 对象(例如,jquery.ui.datepicker-nb-NO.js,其中日期格式为 DD.MM.yyyy 且未由 Date.parse 解析)并初始化它,正确的做法是:

$.validator.addMethod('dateRange', function (value, element, parameterValue) {
        if (this.optional(element) && !value) {
            return true;
        }
        var dateFormat = $(element).datepicker('option', 'dateFormat');
        try {
            var startDate = $.datepicker.parseDate(dateFormat, parameterValue[0]).getTime();
            var endDate = $.datepicker.parseDate(dateFormat, parameterValue[1]).getTime();
            var enteredDate = $.datepicker.parseDate(dateFormat, value).getTime();
            return (startDate <= enteredDate) && (enteredDate <= endDate);
        } catch (error) {
            return true;
        }
    });

I've put parseDate stuff inside try block, because there's no normal way to figure out if the date has been parsed properly.

我已经把 parseDate 的东西放在 try 块中,因为没有正常的方法来确定日期是否被正确解析。

回答by toddmo

Date range min/maxattributes on datetype input

日期范围min/类型max属性dateinput

<!--jquery validate-->
    <script defer src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
    <script defer src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>

<input id="christmas-shopper-reservation" type="date" min="2010-11-29" max="2010-12-15">

<label id="christmas-shopper-reservation-error" class="error" style="display:none;" for="christmas-shopper-reservation"></label>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<!--jquery validate-->
     <script  src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.2.3/jquery.validate.min.js"></script>
     <script  src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.2.3/additional-methods.min.js"></script>

    <input id="christmas-shopper-reservation" type="date" min="2010-11-29" max="2010-12-15">
    
    <label id="christmas-shopper-reservation-error" class="error" style="display:none;" for="christmas-shopper-reservation"></label>