views:

58

answers:

2

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?

A: 

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

David Radcliffe
I don't use constrainInput because I want people to be able to use a slash or dash as a seperator. However, I don't see how using that would allow me to know if someone enters a day that doesn't exist. Such as Feb 30th.
A: 

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: http://stackoverflow.com/questions/2715626/jquery-datepicker-validate-date-mm-dd-yyyy

RememberME