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

前端 未结 13 1286
忘掉有多难
忘掉有多难 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:18

    As mentioned on the addMethod documentation:

    Please note: While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method. If you need lots of slightly different expressions, try to extract a common parameter. A library of regular expressions: http://regexlib.com/DisplayPatterns.aspx

    So yes, you have to add a method for each regular expression. The overhead is minimal, while it allows you to give the regex a name (not to be underestimated), a default message (handy) and the ability to reuse it a various places, without duplicating the regex itself over and over.

    0 讨论(0)
  • 2020-11-22 08:18

    This is working code.

    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;
            }
        });
    }
    
    0 讨论(0)
  • 2020-11-22 08:19

    I had some trouble putting together all the pieces for doing a jQuery regular expression validator, but I got it to work... Here is a complete working example. It uses the 'Validation' plugin which can be found in jQuery Validation Plugin

    <!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>
    
    0 讨论(0)
  • 2020-11-22 08:20

    I got it to work like this:

    $.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            return this.optional(element) || regexp.test(value);
        },
        "Please check your input."
    );
    
    
    $(function () {
        $('#uiEmailAdress').focus();
        $('#NewsletterForm').validate({
            rules: {
                uiEmailAdress:{
                    required: true,
                    email: true,
                    minlength: 5
                },
                uiConfirmEmailAdress:{
                    required: true,
                    email: true,
                    equalTo: '#uiEmailAdress'
                },
                DDLanguage:{
                    required: true
                },
                Testveld:{
                    required: true,
                    regex: /^[0-9]{3}$/
                }
            },
            messages: {
                uiEmailAdress:{
                    required: 'Verplicht veld',
                    email: 'Ongeldig emailadres',
                    minlength: 'Minimum 5 charaters vereist'
                },
                uiConfirmEmailAdress:{
                    required: 'Verplicht veld',
                    email: 'Ongeldig emailadres',
                    equalTo: 'Veld is niet gelijk aan E-mailadres'
                },
                DDLanguage:{
                    required: 'Verplicht veld'
                },
                Testveld:{
                    required: 'Verplicht veld',
                    regex: '_REGEX'
                }
            }
        });
    });
    

    Make sure that the regex is between / :-)

    0 讨论(0)
  • 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.

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

    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

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题