user1791567
user1791567

Reputation: 1428

jQuery validate options don't apply - MVC4

I'm doing unobtrusive form validation in MVC 4 and I'm trying to show errors in a popup rather than in the page. I'm testing the option showErrors and invalidHandler but events never get fired.

When the page is ready this js is call to initialize the validator

$("form").validate({
    showErrors: function (errorMap, errorList) {
        console.warn(errorList);
    },
    invalidHandler: function (event, validator) {
        alert('test');
    }
});

When the user clicks submit validation occurs and errors are shown in the page but I don't see anything in the browser console nor an alert popup.

When I inspect the validator I see that in settings that showErrors and invalidHandler have default values so the options were never applied.

$('form').validate().settings

Help is appreciated.

Upvotes: 1

Views: 369

Answers (2)

user1791567
user1791567

Reputation: 1428

So, this is how I solved my problem.

I figured that MVC was calling the validator before me and as the plugin returns the valitaror if you call it again with new options therefore options never get apply to the validator settings. Also I did not want to apply my settings to all validators so here is.

//-- Validator settings. At this point this validator is already created (for me)
var $vlt = $('form').validate(); // Get validator

 var options = { //-- new options
            onfocusout: false, 
            onkeyup: false, 
            onclick: false,            
            showErrors: function (errorMap, errorList) {
                console.warn(errorList);
    }
 };

 $vlt.settings = $.extend(true, {}, $vlt.settings, options); // apply options

I put this script on a $().ready block in a partial view

Upvotes: 0

Sam Thadhani
Sam Thadhani

Reputation: 587

I had a similar requirement once, what i used to do was add a js popup class from jquery popups and only add it to the element which is invalid.

If you refer to the errorPlacement method you have element and error variables available. You can add popup js class to element there. The method errorPlacement is only called for elements which are invalid based on the validation rules that you have written and here you can control where inline validation message appears and where popup message appears.

Upvotes: 1

Related Questions