jQuery validate: How to add a rule for regular expression validation?

前端 未结 13 1538
忘掉有多难
忘掉有多难 2020-11-22 07:41

I am using the jQuery validation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am m

13条回答
  •  星月不相逢
    2020-11-22 08:25

    we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.

    
    

    therefore we use the following snippet

    $.validator.addMethod(
            "regex",
            function(value, element, regstring) {
                // fast exit on empty optional
                if (this.optional(element)) {
                    return true;
                }
    
                var regParts = regstring.match(/^\/(.*?)\/([gim]*)$/);
                if (regParts) {
                    // the parsed pattern had delimiters and modifiers. handle them. 
                    var regexp = new RegExp(regParts[1], regParts[2]);
                } else {
                    // we got pattern string without delimiters
                    var regexp = new RegExp(regstring);
                }
    
                return regexp.test(value);
            },
            "Please check your input."
    );  
    

    Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).

    PS: there is also bundled plugin for that, https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js

提交回复
热议问题