Validate ZIP code and populate fields automatically jquery validate

Asked

Viewed 768 times

1

How can I validate a zip code and fill in a field, for example the one in the city, using jquery validate?

For example: the field (input) that the user would fill the city would be "disabled" and the value of it would be picked up by a ZIP code validation, I found this free service that returns a JSON output on the CEP information.

  • validate the zip code is easy, it depends a little if it will have - or No, but basically it is 8 numbers so something like this already solves /^\d{8}$/.test('01001000'). Then you make a query in that service and use the return data to fill in the form. There is some specific point that ta having difficulty?

  • In fact, the validation would be if the CEP value "hit" with the return of JSON, and then fill in the fields, I’m using the Jquery Validate plugin.

1 answer

2

To validate you can use a regex.

^\d{5}-\d{3}$

And to fill in the fields you can use a code in this style.

var json={ 
  "cep": "01001-000",
  "logradouro": "Praça da Sé",
  "complemento": "lado ímpar",
  "bairro": "Sé",
  "localidade": "São Paulo",
  "uf": "SP",
  "unidade": "",
  "ibge": "3550308",
  "gia": "1004"
};

for(key in json)
{
  if(json.hasOwnProperty(key))
    $('input[name='+key+']').val(json[key]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" name="cep"/>
  <input type="text" name="logradouro"/>
  <input type="text" name="bairro"/>
  <input type="text" name="localidade"/>
  <input type="text" name="uf"/>
</form>

  • 1

    Thanks for the reply, but how would it be done with the plugin Jquery Validate?

  • @NGTHM4R3 sorry, I didn’t notice the main factor (Jquery Validate). If you don’t get an answer, I can try to search later and post as soon as I get a more direct answer for you.

Browser other questions tagged

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