Manually adding & removing validation errors to jQuery validator

前端 未结 3 1644
北恋
北恋 2021-02-02 06:46

I have a search form & knockout-based grid for results. When search is performed, there is some server-side validation taking place on asp.net mvc, and if model state is not

3条回答
  •  迷失自我
    2021-02-02 07:49

    I did something a bit simpler - basically added the ability to more fully register the error into the validator. I added the following to jquery.validate.js (underneath showErrors):

    addErrors: function (errors) {
            for (var i = 0; i < errors.length; i++) {
                this.errorList.push({
                    element: $(errors[i].element)[0],
                    message: errors[i].message
                });
            }           
            this.showErrors();
        },
    

    then instead of calling form.validate().showErrors() you can do e.g.

    form.validate().addErrors([{
        element: $('#myinput'),
        message: 'A manual error message'
    }]);
    

    Finally because the form may not have been marked as invalid when submitted, you may want to force a validation on keyup or similar:

    $('#myinput').one('keyup', function(){ $(this).valid(); });
    

    (Note: this isn't battle-tested but I'm sure at the very least a solution lies down this way somewhere)

提交回复
热议问题