jQuery Validation plugin. Two custom rules not working

浪子不回头ぞ 提交于 2020-01-06 07:59:27

问题


I'm using jQuery validation engine and I have two custom rules that I need to use for one field. I've tried both of them one by one, they work fine. How do I attach both?

class="validate[required,custom[OFS, onlyLattinLetters], maxSize[140]]"

or

class="validate[required,custom[OFS], custom[onlyLattinLetters], maxSize[140]]"

doesn't work.


回答1:


Instead of inline classes, have you tried declaring them within the plugin initialization function?

$(document).ready(function() {
    $('#myForm').validate({
        rules: {
            myField: { 
                required: true,
                OFS: true,
                onlyLattinLetters: true,
                maxSize: 140
            }
        }
    });
});

EDIT:

I would recommend totally avoiding inline code; I think it's more difficult to maintain, makes your HTML verbose, and it mingles functionality with your presentation styles.

I also removed my example below (see edit history), which I found in the jQuery discussion forum, since I cannot find any official documentation on proper syntax and usage.




回答2:


If you must use inline, use the Add method to create your two custom rules, I'll do one to show

 jQuery.validator.addMethod("onlyLattinLetters", function(value, element) {
 return this.optional(element) || \p{IsBasicLatin}.test(value); 
 // or replace before .test() whatever your regex is 
 }, "Only in Latin numbers please");

then you could use your validation call as such, removing the custom[] from the inline

 class="validate[required, OFS, onlyLattinLetters, maxSize[140]]"

Truely the better method would be Sparky672's validate() plugin initialization but if you must use inline the above works



来源:https://stackoverflow.com/questions/13160201/jquery-validation-plugin-two-custom-rules-not-working

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