jQuery Validation plugin: How to force a certain phone number format ###-###-####

后端 未结 4 1614
后悔当初
后悔当初 2021-02-10 10:34

I have jQuery Validation plugin on a page. When someone types the phone number into the form field, I want the validator to only recognize a certain format:

###-         


        
4条回答
  •  滥情空心
    2021-02-10 10:47

    Simply use the phoneUS rule included in the jQuery Validate plugin's additional-methods.js file.

    DEMO: http://jsfiddle.net/c9zy9/

    $(document).ready(function () {
    
        $('#myform').validate({ // initialize the plugin
            rules: {
                phone_number: {
                    required: true,
                    phoneUS: true
                }
            }
        });
    
    });
    

    Alternatively, instead of including the entire additional-methods.js file, you can just pull out the phoneUS method.

    DEMO: http://jsfiddle.net/dSz5j/

    $(document).ready(function () {
    
        jQuery.validator.addMethod("phoneUS", function (phone_number, element) {
            phone_number = phone_number.replace(/\s+/g, "");
            return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(\+?1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
        }, "Please specify a valid phone number");
    
        $('#myform').validate({ // initialize the plugin
            rules: {
                phone_number: {
                    required: true,
                    phoneUS: true
                }
            }
        });
    
    });
    

提交回复
热议问题