Chris
Chris

Reputation: 28064

jQuery validate plugin with datepicker - invalid date causes datepicker popup on submit

I have a simple MVC3 form that has a date field and client side validation enabled (jquery.validate / jquery.validate.unobtrusive). I've added code to attach a datepicker (jQuery UI) to the date field per the documentation. However, if the datepicker is the last thing I click prior to clicking the submit button and the date field is invalid, it causes the datepicker for that field to automatically show itself. I don't want this. How can I disable?

Edit:

After reviewing the code for the validation plugin, it looks like it tries to manually focus on the last active input control using the focusInvalid() function below:

focusInvalid: function() {
    if( this.settings.focusInvalid ) {
        try {
            $(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
            .filter(":visible")
            .focus()
            // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
            .trigger("focusin");
        } catch(e) {
            // ignore IE throwing errors when focusing hidden elements
        }
    }
},

There appear to be 2 options for dealing with this. One is to set the focusInvalid setting on the validator itself to false. I opted to monkey patch the focusInvalid function instead because it allows me to focus on the FIRST invalid element in the form, not necessarily the last active element.

$('form').data('validator').focusInvalid = function () {
    $(this.currentForm).find('.input-validation-error').first().focus();
};

I'd be interested to hear any other approaches to this problem, however.

Upvotes: 0

Views: 780

Answers (1)

simo
simo

Reputation: 11

If acceptable in your case, you could show the datepicker only using a button, using the following datepicker options:

showOn: 'button', showButtonPanel: true, buttonImage: '<your image file>',
            buttonImageOnly: true,
            buttonText: 'Choose a Date',

If you do it this way the datepicker won't automatically display in case validation fails when submitting the form.

Upvotes: 1

Related Questions