-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
40 lines (32 loc) · 1.22 KB
/
script.js
File metadata and controls
40 lines (32 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const clearForm = (endereco) => {
document.querySelector('#endereco').value = "";
document.querySelector('#bairro').value = "";
document.querySelector('#cidade').value = "";
document.querySelector('#estado').value = "";
}
const preencherForm = (endereco) => {
document.querySelector('#endereco').value = endereco.logradouro;
document.querySelector('#bairro').value = endereco.bairro;
document.querySelector('#cidade').value = endereco.localidade;
document.querySelector('#estado').value = endereco.uf;
}
const eNumero = (numero) => /^[0-9]+$/.test(numero);
const cepValido = (cep) => cep.length == 8 && eNumero(cep);
const searchCep = async() => {
clearForm();
const cep = document.querySelector('#cep').value;
const url = `https://viacep.com.br/ws/${cep}/json/`;
if (cepValido(cep)) {
const dados = await fetch(url);
const endereco = await dados.json();
if (endereco.hasOwnProperty('erro')) {
document.querySelector('#endereco').value = 'CEP não encontrado!';
} else {
preencherForm(endereco);
}
} else {
document.querySelector('#endereco').value = 'CEP incorreto!';
}
//console.log(endereco);
}
document.querySelector('#cep').addEventListener("focusout", searchCep);