How to validate a zip code using jQuery.validate

Asked

Viewed 5,542 times

0

I am not able to validate a ZIP code typed by the user.

I added the following code within the jquery.validete.js

jQuery.validator.addMethod("cep", function(value, element) {
  return this.optional(element) || /^[0-9]{2}.[0-9]{3}-[0-9]{3}$/.test(value);
}, "Por favor, digite um CEP válido");

But if I type: 11.111-111 it accepts, when in fact this zip code does not exist.

  • 1

    Welcome to Sopt Guilherme. Edit your question and group your code using the add code option, I also suggest a tour to learn how to ask: https://answall.com/tour

2 answers

2

Change the regular expression to:

/^[0-9]{5}-[0-9]{3}$/

The value between keys defines the amount of times the characters in brackets will repeat, thus validating the value 11.111-11 with /^[0-9]{2}.[0-9]{3}-[0-9]{3}$/ is correct

1


  • Guilherme, how did you get the value of JSON? and it is possible to fill a field automatically?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.