开发者

jquery datepicker : Validate current input value?

开发者 https://www.devze.com 2023-01-05 18:41 出处:网络
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.

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.

For example:

If someone decides to type in 02/30/2010 I'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).

Does anyone know how this can be done?


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>


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) {}


Although this question is almost two years old, I have recently dealt with a similar solution and found that the Globalize library 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:

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

The Globalize library 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.


Look at the dateFormat and constrainInput options of the datepicker. http://jqueryui.com/demos/datepicker/#option-dateFormat


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.

$.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",
                }
});

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


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

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()))

0

精彩评论

暂无评论...
验证码 换一张
取 消