nick
nick

Reputation: 1246

jQuery Validation methods for zip code

I am trying to validate zip codes in a form field. This method I am applying to the zipcode object will validate the form correctly when the user types in too many or too few, but if they do nothing at all then the placeholder text, "12345", in the form allows the user to pass the validation successfully. So I am trying to add to this code here something like "or == "12345" then return false". Any ideas on how?

jQuery.validator.addMethod('zipcode', function(value, element) {

      return this.optional(element) || !!value.trim().match(/^\d{5}(?:[-\s]\d{4})?$/) || !!value == "12345";

    }, 'Invalid zip code');

Upvotes: 1

Views: 165

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

I think you just want:

return this.optional(element) || 
    (/^\d{5}(?:[-\s]\d{4})?$/.test(value.trim()) && value !== "12345");

or a little more robustly if you are in fact using the placeholder attribute:

return this.optional(element) || 
    (/^\d{5}(?:[-\s]\d{4})?$/.test(value.trim()) && 
           value !== $(element).attr('placeholder'));

I've also replaced match with test, which you should use if you just want to know if a string matches a RegExp.

Upvotes: 1

Related Questions