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

前端 未结 13 1289
忘掉有多难
忘掉有多难 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条回答
  •  -上瘾入骨i
    2020-11-22 08:30

    Thanks to the answer of redsquare I added a method like this:

    $.validator.addMethod(
            "regex",
            function(value, element, regexp) {
                var re = new RegExp(regexp);
                return this.optional(element) || re.test(value);
            },
            "Please check your input."
    );
    

    now all you need to do to validate against any regex is this:

    $("#Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$" })
    

    Additionally, it looks like there is a file called additional-methods.js that contains the method "pattern", which can be a RegExp when created using the method without quotes.


    Edit

    The pattern function is now the preferred way to do this, making the example:

     $("#Textbox").rules("add", { pattern: "^[a-zA-Z'.\\s]{1,40}$" })
    

    http://bassistance.de/jquery-plugins/jquery-plugin-validation/

    http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.js

提交回复
热议问题