Problem when using isNaN

Asked

Viewed 46 times

-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.

1 answer

0


In the documentation of parseInt() explains why this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

If parseint finds a character other than a numeral in the base specified, it ignores it and all subsequent characters and returns the integer value parsed to that point. parseint trunca numbers for integer values. Spaces at start and end are allowed.

That is, if it starts with a digit, it is converted until it finds something invalid, and the rest is discarded, examples:

// primeiro caractere inválido, Nan
console.log(parseInt("!1a5b")); 
console.log(parseInt("a1a5b")); 
console.log(parseInt("x1a5b"));

// primeiro caracter válido, converte tudo, ou até encontrar um inválido, o resto é ignorado
console.log(parseInt("1!1a5b")); 
console.log(parseInt("12a1a5b")); 
console.log(parseInt("123x1a5b"));

  • What would be a viable option for me to fix my code ? thanks for the feed

  • 1

    use a regular Expression to check if you only have digits, for example /^[0-9]+$/.test("123"), in your code if(!/^[0-9]+$/.test(numeroCep.value))

  • 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.

  • 1

    then you must be doing something wrong in if or input, look at this example: https://jsfiddle.net/htcmfz67/

  • It worked...in place of parseint I put Number...thank you very much

  • 1

    @Care ayrtongomes. Number('123.3213') will work, but you want a whole number...

  • 1

    @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

  • 1

    @Ayrtongomes remove this Number, will not use the number for any calculation, if it is only to validate the regex will already do this

  • regex was not validating with parseint...was having the same problem of deleting strings and keeping the first number

  • 1

    "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

  • Sorry, it was inattentive on my part...I removed the Number and it works normally. Thank you very much

Show 6 more comments

Browser other questions tagged

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