Conflict between jQuery Validate and Masked Input

后端 未结 7 661
梦谈多话
梦谈多话 2020-12-08 10:40

I\'ve got a form that\'s using both jQuery Validate and Masked Input for phone number and US zip code fields.

For example, for a US zip code, Masked Input allows only

7条回答
  •  旧巷少年郎
    2020-12-08 11:02

    I had faced same issue and I spend two hours to make a proper solution. Finally, I made a proper code. You can use it

    For ZIP code.

    $.validator.addMethod("zipcode", function(postalcode, element) {
                //removes placeholder from string
                postalcode = postalcode.replace(/[^0-9]/g, "");
                //validates postalcode.
                return this.optional(element) || postalcode.match(/^\d{5}$|^\d{5}\-\d{4}$/);
            }, "Please specify a valid zip code");
    

    If you want to increase or decrease zip length then change postalcode.match(/^\d{5}$|^\d{5}-\d{4}$/); number according to your requirement.

    For phone same code will be used but you need to change only numbers like postalcode.match(/^\d{10}$|^\d{10}-\d{9}$/);

    $.validator.addMethod("phone_length", function(phoneno, element) {
                    //removes all special characters
                    phoneno= phoneno.replace(/[^0-9]/g, "");
                    return this.optional(element) || phoneno.match(/^\d{10}$|^\d{10}\-\d{9}$/);
                }, "Please enter a valid phone");
    

    I hope this code will help you a lot. If you want to know how to call then simply add zipcode:true in your validation field

提交回复
热议问题