0

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?

4
  • i already tried this but nothing changed - odd, seeing as that actually does what you'd expect - of course, I may be misunderstanding what you want ... and Number("") is zero of course - perhaps you should check document.getElementById("inputNumber").value.length to see if it's empty Commented Jan 27 at 2:35
  • yes, I can receive 0 on this way, but if I click on the submit button without any value, I also receive 0, which I don't want
    – Artur
    Commented Jan 27 at 2:40
  • 1
    because as I said Number("") IS zero - you'll want to check the length of the actual input of course Commented Jan 27 at 2:42
  • !inputElement && inputElement != 0 should be !inputElement || Number(inputElement) == 0
    – Barmar
    Commented Jan 27 at 17:33

1 Answer 1

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

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.