Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger validation to occur on jQuery UI datepicker once a date has been selected?

I have some client-side validation that checks to ensure that the EndDate is greater than or equal to StartDate. The validation works, but it's not firing as I would like it to. I would like it to fire as soon as a date is selected on the datepicker for EndDate. How can I accomplish this? I've tried the following:

Datepicker code:

$(".datepicker").datepicker({
    changeMonth: true,
    changeYear: true,
    onClose: function () {
        $(this).focusout();
    }
});

Validation code:

$("#EndDate").focusout(function () {
    jQuery.validator.addMethod('datetimegreaterthanorequal', function (value, element, params) {
        var startDateValue = $(params.element).val();

        return Date.parse(value) >= Date.parse(startDateValue);
    }, '');

    jQuery.validator.unobtrusive.adapters.add('datetimegreaterthanorequal', ['startdate'], function (options) {
        var prefix = options.element.name.substr(0, options.element.name.lastIndexOf('.') + 1),
            other = options.params.startdate,
            fullOtherName = appendModelPrefix(other, prefix),
            element = $(options.form).find(':input[name=' + fullOtherName + ']')[0];

        options.rules['datetimegreaterthanorequal'] = {
            element: element
        };
        if (options.message) {
            options.messages['datetimegreaterthanorequal'] = options.message;
        }
    });

    function appendModelPrefix(value, prefix) {
        if (value.indexOf('*.') === 0) {
            value = value.replace('*.', prefix);
        }
        return value;
    }
})
like image 936
The Vanilla Thrilla Avatar asked May 07 '13 13:05

The Vanilla Thrilla


2 Answers

Although the answer from Mark will work, you should note that it will validate the entire form. If you just want to validate the related input field, you would be better off doing:

$(".datepicker").datepicker({
    onSelect: function () {
        $(this).trigger("focus").trigger("blur");
    }
});

This fakes the user clicking inside the input field and leaving it again.

like image 112
Rebecca Avatar answered Oct 24 '22 02:10

Rebecca


You are assigning the validators inside of our .focusout() event. Remove that block completely as you want them assigned only once.

You can easily trigger validation on the onSelect option like the following:

$(".datepicker").datepicker({
    changeMonth: true,
    changeYear: true,
    onSelect: function () {
        $("#myForm").valid();
    }
});
like image 32
Mark Coleman Avatar answered Oct 24 '22 01:10

Mark Coleman