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

后端 未结 4 1599
后悔当初
后悔当初 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:53

    @Sparky's suggestion is good if you are a little flexible, but just in case you want just that format, you can add a custom rule:

    $.validator.addMethod('customphone', function (value, element) {
        return this.optional(element) || /^\d{3}-\d{3}-\d{4}$/.test(value);
    }, "Please enter a valid phone number");
    
    $(document).ready(function () {
        $("#myform").validate({
            rules: {
                field1: 'customphone'
            }
        });
    });
    

    Example: http://jsfiddle.net/kqczf/16/

    You can easily make this into a custom class rule. This way you could just add a class to each input that you want to have the rule and possibly omit the rules object from the validate call:

    $(document).ready(function () {
        $("#myform").validate();
    });
    
    
    

    Example: http://jsfiddle.net/kqczf/17/

提交回复
热议问题