Override jQuery validate default settings in MVC4

痞子三分冷 提交于 2019-12-05 21:42:28

I finally make it work as suggested by Bruce. The trick is to remove the old handler before hookup your custom one. You can override other settings the same way. Microsoft should speed up to fix its jquery.validate.unobtrusive.js to work with jquery.validate. It has been 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();
        }
    });
});

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

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

you just get the already created validator instance back 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' invalidHandler function, so you won't get that part of the 'unobtrusive' functionality.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!