Jquery datepicker:验证日期 mm/dd/yyyy

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

Jquery datepicker: validate date mm/dd/yyyy

asp.netjquerydatepicker

提问by Nick Kahn

I have a textbox and a datepicker next to it and I am using asp.net and the user can enter the date as well select the date from datepicker.

我旁边有一个文本框和一个日期选择器,我正在使用 asp.net,用户可以输入日期以及从日期选择器中选择日期。

How would you validate if the date is entered correct?

您将如何验证输入的日期是否正确?

  <script type="text/javascript"> 
        $(document).ready(function () { 
            $('#<%=StartDate.ClientID%>').datepicker({ showOn: 'button', 
                    buttonImage: '../images/Calendar.png', 
                    buttonImageOnly: true, onSelect: function () { }, 
                    onClose: function () { $(this).focus(); } 
            }); 
        }); 
    </script> 

采纳答案by dochoffiday

If you're using ASP.NET, you can use an ASP.NET Compare Validator [ASP.NET Date Validator].

如果您使用的是 ASP.NET,则可以使用 ASP.NET 比较验证器 [ ASP.NET 日期验证器]。

<asp:TextBox ID="tb" runat="server"></asp:TextBox>

<asp:CompareValidator ID="cv" runat="server" 
ControlToValidate="tb" ErrorMessage="* Please enter a valid date!" Text="*" 
Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>

**** Update**

**** 更新**

I took the javascript that was executed by the Compare Validator above and wrapped a custom jQuery Validation method around it:

我采用了由上面的比较验证器执行的 javascript 并在它周围包裹了一个自定义的 jQuery 验证方法:

<script type="text/javascript">
    $(document).ready(function () {

        $.validator.addMethod("truedate", function (value, element, params) {
            function GetFullYear(year, params) {
                var twoDigitCutoffYear = params.cutoffyear % 100;
                var cutoffYearCentury = params.cutoffyear - twoDigitCutoffYear;
                return ((year > twoDigitCutoffYear) ? (cutoffYearCentury - 100 + year) : (cutoffYearCentury + year));
            }

            var yearFirstExp = new RegExp("^\s*((\d{4})|(\d{2}))([-/]|\. ?)(\d{1,2})\4(\d{1,2})\.?\s*$");
            try {
                m = value.match(yearFirstExp);
                var day, month, year;
                if (m != null && (m[2].length == 4 || params.dateorder == "ymd")) {
                    day = m[6];
                    month = m[5];
                    year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
                }
                else {
                    if (params.dateorder == "ymd") {
                        return null;
                    }
                    var yearLastExp = new RegExp("^\s*(\d{1,2})([-/]|\. ?)(\d{1,2})(?:\s|\2)((\d{4})|(\d{2}))(?:\s\u0433\.)?\s*$");
                    m = value.match(yearLastExp);
                    if (m == null) {
                        return null;
                    }
                    if (params.dateorder == "mdy") {
                        day = m[3];
                        month = m[1];
                    }
                    else {
                        day = m[1];
                        month = m[3];
                    }
                    year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
                }
                month -= 1;
                var date = new Date(year, month, day);
                if (year < 100) {
                    date.setFullYear(year);
                }
                return (typeof (date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
            }
            catch (err) {
                return null;
            }
        }, "Please enter an actual date.");

        $("#form1").validate();

        $("#one").rules('add',
        {
            truedate: {
                cutoffyear: '2029',
                dateorder: 'mdy'
            }
        });
    });

</script>

<input id="one" />

回答by katrin

I use this handler for validate input:

我使用这个处理程序来验证输入:

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

Hope, it'll be useful for somebody

希望对某人有用

回答by Trawler

I'm using a mix of Katrin & Doc Holiday's approach, using the datepicker control's parseDate utility method in a custom validator I've called isDate.

我混合使用 Katrin 和 Doc Holiday 的方法,在我称为 isDate 的自定义验证器中使用 datepicker 控件的 parseDate 实用程序方法。

Just change the format argument in parseDate to the appropriate value (reference: http://docs.jquery.com/UI/Datepicker/parseDate).

只需将 parseDate 中的格式参数更改为适当的值(参考:http://docs.jquery.com/UI/Datepicker/parseDate )。

    $(document).ready(function()
    {
        $.validator.addMethod('isDate', function(value, element)
        {
            var isDate = false;
            try
            {
                $.datepicker.parseDate('dd/mm/yy', value);
                isDate = true;
            }
            catch (e)
            {

            }
            return isDate;
        });

        $("#form1").validate();

        $("#dateToValidate").rules("add", { isDate: true, messages: {isDate: "Date to Validate is invalid."} });
    });

It's probably not best practice for the validator to be referencing a UI control but what the heck. :)

验证器引用 UI 控件可能不是最佳实践,但这到底是什么。:)

回答by Rabbott

Since you are already using jquery, you could check out http://bassistance.de/jquery-plugins/jquery-plugin-validation/which has great flexibility for validations..

由于您已经在使用 jquery,您可以查看http://bassistance.de/jquery-plugins/jquery-plugin-validation/,它具有很大的验证灵活性。