Dynamic jQuery Validate error messages with AddMethod based on the element

前端 未结 6 1557
一向
一向 2020-11-27 19:14

Let\'s say I have a custom AddMethod to jQuery Validate like:

$.validator.addMethod(\'min-length\', function (val, element) {
    // do stuff

// the error m         


        
6条回答
  •  情歌与酒
    2020-11-27 19:20

    If Barmar's answer doesn't work for you, it is probably because your settings for the element already contains an error message(set from the server in asp.net MVC for example)

    So the jQuery.validate code will ignore the new default set by the second parameter to $.validator.addMethod

    A way around it is to do the following:

    $.validator.addMethod('min-length', function (val, element) {
       this.settings.messages[element.name]['min-length'] = function () { return 'put your custom message here'; };
    
       return this.optional(element) || val.length >= $(element).data('min');
    });
    

提交回复
热议问题