Validate zip code and fill in fields automatically jquery validate

1

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

For example: the field (input) that the user would fill the city would be disabled and the value of the same would be taken by a validation of the CEP, I found this free service which returns a JSON output on the zip code information.

    
asked by anonymous 21.09.2016 / 18:51

1 answer

2

To validate you can use a regex .

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

And to fill in the fields you can use 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><inputtype="text" name="cep"/>
  <input type="text" name="logradouro"/>
  <input type="text" name="bairro"/>
  <input type="text" name="localidade"/>
  <input type="text" name="uf"/>
</form>
    
21.09.2016 / 20:24