jquery datepicker:验证当前输入值?

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

jquery datepicker : Validate current input value?

jqueryjquery-uidatepicker

提问by user169867

I've been using the Datepicker plugin from jQuery UI. I want to be able to validate if the input textbox it is attached to currently has a valid date or not.

我一直在使用 jQuery UI 中的 Datepicker 插件。我希望能够验证它所附加的输入文本框当前是否具有有效日期。

For example:

例如:

If someone decides to type in 02/30/2010I'd like to be able to somehow ask the plugin if that current input value is a valid date (which it is not in this case).

如果有人决定输入,02/30/2010我希望能够以某种方式询问插件当前输入值是否是有效日期(在这种情况下不是)。

Does anyone know how this can be done?

有谁知道如何做到这一点?

回答by Humayoo

You can solve your problem by making text box read only and set date format as you like. So User is not able to type anything in text box, user only select correct date format(which you set) from date picker. Please see the below example.

您可以通过将文本框设为只读并根据需要设置日期格式来解决您的问题。因此用户无法在文本框中键入任何内容,用户只能从日期选择器中选择正确的日期格式(您设置的)。请看下面的例子。

<p>Date: <input type="text" id="datepicker" size="30" readonly="readonly"/></p>    
<script>
$(function() {
    $( "#datepicker" ).datepicker();
    $( "#datepicker" ).datepicker( "option", "dateFormat",'yy-mm-dd');
});
</script>

回答by Alexander

It's very easy

这很容易

let value = $(this).val();
let format = $(this).datepicker('option', 'dateFormat');
let valueIsValid = false;
try {
    $.datepicker.parseDate(format, value);
    valueIsValid = true;
}
catch (e) {}

回答by Eric Brenden

Although this question is almost two years old, I have recently dealt with a similar solution and found that the Globalizelibrary is the best approach. For example, suppose you have a textbox that has a jQueryUI datepicker attached to it. When focus is lost on the textbox, you can use Globalize to validate the entered date. In this case the textbox is blanked if the date is invalid or put in a standard format if the date is valid:

虽然这个问题已经快两年了,但我最近处理了一个类似的解决方案,发现Globalize库是最好的方法。例如,假设您有一个附加了 jQueryUI 日期选择器的文本框。当焦点在文本框上丢失时,您可以使用 Globalize 来验证输入的日期。在这种情况下,如果日期无效,则文本框为空白,如果日期有效,则以标准格式输入:

$('#myDateTextBox').blur(function () {
    var parsedDate = Globalize.parseDate($(this).val());
    if (parsedDate == null) {
        $(this).val('');
    } 
    else {
        $(this).val(Globalize.format(parsedDate, 'd'));
    }

The Globalizelibrary allows you to specify a culture (using the language of the request ideally) so the user can enter a date in the format for their culture.

Globalize库允许您指定文化(理想情况下使用请求的语言),以便用户可以按其文化的格式输入日期。

回答by David Radcliffe

Look at the dateFormatand constrainInputoptions of the datepicker. http://jqueryui.com/demos/datepicker/#option-dateFormat

查看日期选择器的dateFormatconstrainInput选项。 http://jqueryui.com/demos/datepicker/#option-dateFormat

回答by RememberME

I added a "truedate" method to the validator. I'd love to credit whoever's code this is, but I don't remember where I found it.

我向验证器添加了一个“truedate”方法。我很想感谢这是谁的代码,但我不记得我在哪里找到的。

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

    if (value == null || value == '')
        return true;
    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)) {
            day = m[6];
            month = m[5];
            year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3]));
        }
        else {
            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;
            }
            day = m[3];
            month = m[1];
            year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6]));
        }
        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.");

$('form').validate({
                rules: {
                    insurance_GL: "truedate",
                },
                messages: {
                    insurance_GL: "Insurance GL date is not valid",
                }
});

EDITI must have gotten it from here: Jquery datepicker: validate date mm/dd/yyyy

编辑我一定是从这里得到的: Jquery datepicker: validate date mm/dd/yyyy

回答by Arashsoft

It is possible to use JS Dateto validate your date String.

可以使用 JSDate来验证您的日期字符串。

var myDate = new Date(userInputString);

if (myDate == "Invalid Date"){
 // user input is invalid
}

Also note that (myDate === "Invalid Date")returns false even for invalid dates. Using == works fine however the correct way to check is (isNaN( d.getTime()))

另请注意,(myDate === "Invalid Date")即使对于无效日期,也会返回 false。使用 == 工作正常,但正确的检查方法是(isNaN( d.getTime()))