Conflict between jQuery Validate and Masked Input

后端 未结 7 655
梦谈多话
梦谈多话 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:07

    I was actually looking for an answer to this exact question. Ended up figuring out a more reliable workaround.

    Since I am defining my own validator method for the zipcode I modified it so that it would remove the hyphen if the length of the zipcode was 6 after I removed the placeholder from the value.

    It looked like this:

    $.validator.addMethod("zipcode", function(postalcode, element) {
                //removes placeholder from string
                postalcode = postalcode.split("_").join("");
    
                //Checks the length of the zipcode now that placeholder characters are removed.
                if (postalcode.length === 6) {
                    //Removes hyphen
                    postalcode = postalcode.replace("-", "");
                }
                //validates postalcode.
                return this.optional(element) || postalcode.match(/^\d{5}$|^\d{5}\-\d{4}$/);
            }, "Please specify a valid zip code");
    

    So the postalcode I am validating will have the placeholders added by the input plugin and the hyphen removed if the zipcode that is entered only has 5 numerical digits (6 including the hyphen). So it will validate it properly.

提交回复
热议问题