-1
Hello, I created a script that consumes a public API to query ceps and returns the result in an HTML.
The code:
async function buscarCEP() {
let numeroCep = document.querySelector('.numeroCEP')
numeroCep.value = parseInt(numeroCep.value)
if (isNaN(numeroCep.value)) {
alert('Digite apenas números sem traços,pontos,letras ou símbolos');
return location.reload();
}
else {
let cep = await fetch(`https://viacep.com.br/ws/${numeroCep.value}/json/`);
let resultado = await cep.json();
retornarHtml(resultado)
}
}
function retornarHtml(resultado) {
let html = ''
html += `<b> Rua: </b> ${resultado.logradouro} <br/> <br/>`
html += `<b>Bairro: </b> ${resultado.bairro} <br/> <br/>`
html += `<b>CEP: </b> ${resultado.cep} <br/> <br/>`
html += `<b>Cidade: </b>${resultado.localidade} <br/> <br/>`
html += `<b>Estado: </b>${resultado.uf} <br/> <br/>`
html += `<b>DDD: </b> ${resultado.ddd} <br/> <br/>`
document.querySelector('.resultadoPesquisa').innerHTML = html
document.querySelector('.resultadoPesquisa').style.display = 'block';
}
It happens as follows: If I type in input: a54a54aa4, my condition is met and executes the if code
Now if I do: 1a 587a87a, it erases everything, it is only the number 1 and the condition is not satisfied
I hit my head for a long time and I couldn’t fix it.
What would be a viable option for me to fix my code ? thanks for the feed
– Ayrton Gomes
use a regular Expression to check if you only have digits, for example
/^[0-9]+$/.test("123")
, in your codeif(!/^[0-9]+$/.test(numeroCep.value))
– Ricardo Pontual
It’s still the same thing. I’d have to modify something in the code you gave me, in this case . test ?? Excuse my ignorance 'cause I don’t know about regex yet.
– Ayrton Gomes
then you must be doing something wrong in if or input, look at this example: https://jsfiddle.net/htcmfz67/
– Ricardo Pontual
It worked...in place of parseint I put Number...thank you very much
– Ayrton Gomes
@Care ayrtongomes.
Number('123.3213')
will work, but you want a whole number...– Rafael Tavares
@Rafaeltavares, regex will pick up, it only accepts digits, but it was well noticed that from Number :) Besides, it doesn’t even need this conversion if you will pass the parameter to the API
– Ricardo Pontual
@Ayrtongomes remove this Number, will not use the number for any calculation, if it is only to validate the regex will already do this
– Ricardo Pontual
regex was not validating with parseint...was having the same problem of deleting strings and keeping the first number
– Ayrton Gomes
"regex was not validating with parseint" as I commented above, you don’t need that paerseint, regex suffice to validate, you don’t need value as number, you don’t need parseint or number
– Ricardo Pontual
Sorry, it was inattentive on my part...I removed the Number and it works normally. Thank you very much
– Ayrton Gomes