Override jQuery to validate default parameters in MVC4

To override the request validation plugin, in the plaugsin doc , the recommended way is:

$(".selector").validate({
    invalidHandler: function(form, validator) {
      var errors = validator.numberOfInvalids();
      if (errors) {
        var message = errors == 1
          ? 'You missed 1 field. It has been highlighted'
          : 'You missed ' + errors + ' fields. They have been highlighted';
        $("div.error span").html(message);
        $("div.error").show();
      } else {
        $("div.error").hide();
      }
    }
})

      

However, it doesn't work in MVC4 with jquery-1.7.1.js. It seems jquery.validate.unobtrusive.js disallows calling the override descriptor. If this file is not included, the override descriptor is called and a message is displayed. Anyone have the same problem?

+3


source to share


2 answers


I will finally do it as Bruce suggested . The trick is to remove the old handler before attaching your own. You can override other settings in the same way. Microsoft needs to speed up jquery.validate.unobtrusive.js to work with jquery.validate. Reported unobtrusive [version = "2.0.20710.0"] breaks jquery-1.9.0 .



$('form').each(function() {
    $(this).unbind("invalid-form.validate"); // remove old handler!!!!
    $(this).bind("invalid-form.validate", function(e, validator) {
        //alert("ok");
        var errors = validator.numberOfInvalids();
        if (errors) {
            var message = errors == 1
                ? 'You missed 1 field. It has been highlighted'
                : 'You missed ' + errors + ' fields.  They have been highlighted';
            $("div.error span").html(message);
            $("div.error").show();
        } else {
            $("div.error").hide();
        }
    });
});

      

+3


source


The reason this doesn't work is because the validator has already been created by an unobtrusive plugin, so when you call

$(".selector").validate({..})

      

you just get an already created validation instance and your options are not applied. However, I think you can change the settings this way.



<script>
    $(function () {  

        // get the validator instance
        var v = $('form').validate();

        // overwrite the invalidHandler with your own function
        v.settings.invalidHandler = function(form, validator) {
          // your stuff here
        };
    });
</script>

      

Note that this overwrites the "unobtrusive" function invalidHandler, so you won't get this piece of "unobtrusive" functionality.

+1


source







All Articles