jquery datepicker:验证日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27528068/
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 11:25:18  来源:igfitidea点击:

jquery datepicker: validate date

jqueryjquery-ui-datepicker

提问by Manlio

i have set a jquery class:

我已经设置了一个 jquery 类:

$(function() {
            $( ".datepickerIT" ).datepicker({
                showOtherMonths: true,
                selectOtherMonths: true,
                showAnim: "clip",
                dateFormat: "dd/mm/yy",
                minDate: "01/01/1925",
                maxDate: "31/12/2050",
                changeMonth: true,
                changeYear: true,
                yearRange: "1925:2050",
                regional: "it"                      
            });
        });

I want to add a date check control that alert if user input not is a valid date

我想添加一个日期检查控件,如果用户输入不是有效日期,则该控件会发出警报

How can add to the class ".datepickerIT" a check like this?

如何将这样的支票添加到“.datepickerIT”类中?

onClose: function(dateText, inst) {
        try {
            $.datepicker.parseDate('dd/mm/yy', dateText);
        } catch (e) {
            alert(e);
        };

And what plugin i must include into head section?

我必须在 head 部分包含什么插件?

回答by Razan Paul

Date.parseis not recommend to use as there are still many differences in how different hosts parse date strings. [1][2]

Date.parse不建议使用,因为不同主机解析日期字符串的方式仍有很多差异。[1][2]

I would use moment for date validation.

我会使用时刻进行日期验证。

moment(newDate, 'DD/MM/YYYY', true).isValid()

jsfiddle: http://jsfiddle.net/dw8xyzd4/

jsfiddle:http: //jsfiddle.net/dw8xyzd4/

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse[2] Why does Date.parse give incorrect results?

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse[2]为什么 Date.parse 给出不正确的结果?

回答by Gaurav Kalyan

You can validate the date in following ways (you don't need a plugin for it):-

您可以通过以下方式验证日期(您不需要插件):-

$(document).ready(function(){
    $("#datepicker").datepicker();
    $("#datepicker").blur(function(){
        val = $(this).val();
        val1 = Date.parse(val);
        if (isNaN(val1)==true && val!==''){
           alert("error")
        }
        else{
           console.log(val1);
        }
    });
});

Working fiddle

工作小提琴

UPDATE: Correct approach is mentioned by @Razan Paul

更新:@Razan Paul 提到了正确的方法

回答by Y.B.

Date.parse() does not support dd/mm/yyyy and datepicker getDate sets date to current on any parse error hence this bespoke check using new Date(yyyy, mm, dd) to verify date parts are consistent after conversion:

Date.parse() 不支持 dd/mm/yyyy 并且 datepicker getDate 在任何解析错误时将日期设置为当前,因此此定制检查使用 new Date(yyyy, mm, dd) 来验证转换后日期部分是否一致:

$(function() {
    $(".datepickerIT")
        .datepicker({
            showOtherMonths: true,
            selectOtherMonths: true,
            showAnim: "clip",
            dateFormat: "dd/mm/yy",
            minDate: "01/01/1925",
            maxDate: "31/12/2050",
            changeMonth: true,
            changeYear: true,
            yearRange: "1925:2050",
            regional: "it"                      
        })
        .on('blur', function() { // This check is for dd/mm/yyyy format but can be easily adapted to any other
            if(this.value.match(/\d{1,2}[^\d]\d{1,2}[^\d]\d{4,4}/gi) == null)
                alert('Invalid date format');
            else {
                var t = this.value.split(/[^\d]/);
                var dd = parseInt(t[0], 10);
                var m0 = parseInt(t[1], 10) - 1; // Month in JavaScript Date object is 0-based
                var yyyy = parseInt(t[2], 10);
                var d = new Date(yyyy, m0, dd); // new Date(2017, 13, 32) is still valid
                if(d.getDate() != dd || d.getMonth() != m0 || d.getFullYear() != yyyy)
                    alert('Invalid date value');
            }
        });
});

回答by Anuj Dubey

$(document).ready(function(){

//  Check in date 
    $("#in" ).datepick({
        dateFormat: "mm/dd/yy",
        minDate:"0+1",
        maxDate: "2years",
        changeMonth:true, 
        changeYear:true,    
        onSelect:function(date_text,inst){
            var from = new Date(date_text);
            $( "#out" ).datepicker( "option", "minDate",from);
        }       


    });

//  Check out date  



});

Note:-Here in is your field name and datepick is your plugin name.

注意:-这里是您的字段名称,datepick 是您的插件名称。