Let receive 0 but not invalid values

46 Views Asked by At

I have a input that i want to recive any number (dont matter if its negative, float, long) i code this to now allow null, undefined or empty values, but if I enter 0 it is read as empty

const inputElement = Number(document.getElementById("inputNumber").value);
  if (!inputElement) {
    window.alert("Insira um valor válido");
    return;
  }

i already tried this but dont work

if (!inputElement && inputElement != 0){
  window.alert("Insira um valor válido");
  return;
 }

Does anyone know how to differentiate 0 from empty or vice versa?

1

There are 1 best solutions below

0
cpio On
 if (inputElement.length && !isNaN(+inputElement) && inputElement !== null)

This checks for string length, possible null value, and non-numeric input. The plus sign casts inputElement to number.