我正在使用jQuery验证插件。伟大的东西!我想迁移我现有的ASP。NET解决方案使用jQuery代替ASP。净验证器。我缺少正则表达式验证器的替换。我希望能够做到这样:

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

我如何添加一个自定义规则来实现这一点?


当前回答

这是工作代码。

function validateSignup()
{   
    $.validator.addMethod(
            "regex",
            function(value, element, regexp) 
            {
                if (regexp.constructor != RegExp)
                    regexp = new RegExp(regexp);
                else if (regexp.global)
                    regexp.lastIndex = 0;
                return this.optional(element) || regexp.test(value);
            },
            "Please check your input."
    );

    $('#signupForm').validate(
    {

        onkeyup : false,
        errorClass: "req_mess",
        ignore: ":hidden",
        validClass: "signup_valid_class",
        errorClass: "signup_error_class",

        rules:
        {

            email:
            {
                required: true,
                email: true,
                regex: /^[A-Za-z0-9_]+\@[A-Za-z0-9_]+\.[A-Za-z0-9_]+/,
            },

            userId:
            {
                required: true,
                minlength: 6,
                maxlength: 15,
                regex: /^[A-Za-z0-9_]{6,15}$/,
            },

            phoneNum:
            {
                required: true,
                regex: /^[+-]{1}[0-9]{1,3}\-[0-9]{10}$/,
            },

        },
        messages: 
        {
            email: 
            {
                required: 'You must enter a email',
                regex: 'Please enter a valid email without spacial chars, ie, Example@gmail.com'
            },

            userId:
            {
                required: 'Alphanumeric, _, min:6, max:15',
                regex: "Please enter any alphaNumeric char of length between 6-15, ie, sbp_arun_2016"
            },

            phoneNum: 
            {
                required: "Please enter your phone number",
                regex: "e.g. +91-1234567890"    
            },

        },

        submitHandler: function (form)
        {
            return true;
        }
    });
}

其他回答

我们主要使用jquery验证插件的标记符号,张贴的样本并不适用于我们,当标志出现在正则表达式中,例如。

<input type="text" name="myfield" regex="/^[0-9]{3}$/i" />

因此,我们使用下面的代码片段

$.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."
);  

当然,现在可以将这段代码与上面的代码结合起来,以允许将RegExp对象传递到插件中,但因为我们不需要它,所以我们把这个练习留给读者;-)。

PS:也有捆绑插件,https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js

这对我来说是有效的,作为验证规则之一:

    Zip: {
                required: true,
                regex: /^\d{5}(?:[-\s]\d{4})?$/
            }

希望能有所帮助

你可以使用extra -methods.js文件中定义的模式。注意这个additional-methods.js文件必须包含在jQuery验证依赖之后,然后你就可以使用它了

$("#frm").validate({ rules: { Textbox: { pattern: /^[a-zA-Z'.\s]{1,40}$/ }, }, messages: { Textbox: { pattern: 'The Textbox string format is invalid' } } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script> <form id="frm" method="get" action=""> <fieldset> <p> <label for="fullname">Textbox</label> <input id="Textbox" name="Textbox" type="text"> </p> </fieldset> </form>

我有一些麻烦把所有的部分做一个jQuery正则表达式验证器,但我得到了它的工作…下面是一个完整的工作示例。它使用“验证”插件,可以在jQuery验证插件中找到

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="http://YOURJQUERYPATH/js/jquery.js" type="text/javascript"></script>
    <script src="http://YOURJQUERYPATH/js/jquery.validate.js" type="text/javascript"></script>
    <script type="text/javascript">

        $().ready(function() {
            $.validator.addMethod("EMAIL", function(value, element) {
                return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
            }, "Email Address is invalid: Please enter a valid email address.");

            $.validator.addMethod("PASSWORD",function(value,element){
                return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
            },"Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");

            $.validator.addMethod("SUBMIT",function(value,element){
                return this.optional(element) || /[^ ]/i.test(value);
            },"You did not click the submit button.");

            // Validate signup form on keyup and submit
            $("#LOGIN").validate({
                rules: {
                    EMAIL: "required EMAIL",
                    PASSWORD: "required PASSWORD",
                    SUBMIT: "required SUBMIT",
                },
            });
        });
    </script>
</head>
<body>
    <div id="LOGIN_FORM" class="form">
        <form id="LOGIN" name="LOGIN" method="post" action="/index/secure/authentication?action=login">
            <h1>Log In</h1>
            <div id="LOGIN_EMAIL">
                <label for="EMAIL">Email Address</label>
                <input id="EMAIL" name="EMAIL" type="text" value="" tabindex="1" />
            </div>
            <div id="LOGIN_PASSWORD">
                <label for="PASSWORD">Password</label>
                <input id="PASSWORD" name="PASSWORD" type="password" value="" tabindex="2" />
            </div>
            <div id="LOGIN_SUBMIT">
                <input id="SUBMIT" name="SUBMIT" type="submit" value="Submit" tabindex="3" />
            </div>
        </form>
    </div>
</body>
</html>

你可以使用addMethod()

e.g

$.validator.addMethod('postalCode', function (value) { 
    return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value); 
}, 'Please enter a valid US or Canadian postal code.');

这里有好文章https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/