10

If a user types an invalid value (ex: "1.2.3") into an <input type=number>, then Chrome and Firefox report the <input>'s value property as "" rather than "1.2.3".

So, how do I tell if the user typed in an invalid number into the <input> or just left it blank?

I tried using the valueAsNumber property but it's NaN in both cases.

function showInputValue() {
  const inputValue = document.getElementById("numberInput").value;
  const inputValueAsNumber = document.getElementById("numberInput").valueAsNumber;
  
  console.log(`value is: "${inputValue}"\nvalueAsNumber is: "${inputValueAsNumber}"`);
}

document.getElementById("btn").addEventListener("click", showInputValue)
<input type="number" id="numberInput" placeholder="try entering text"/>
<button id="btn">Show value</button>
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Bill Keese
  • 1,792
  • 14
  • 29

3 Answers3

8

Your input element has the validity property implementing the ValidityState interface:

ValidityState {
  badInput: true,
  customError: false,
  patternMismatch: false,
  rangeOverflow: false,
  rangeUnderflow: false,
  stepMismatch: false,
  tooLong: false,
  tooShort: false,
  typeMismatch: false,
  valid: false,
  valueMissing: false
}

From here you can study all validity states (valueMissing, badInput, etc...)

You can get a reference to your input using document.querySelector.

In your case the empty input will set the valueMissing flag, and the "1.2.3" input will set the badInput flag.

Boann
  • 48,794
  • 16
  • 117
  • 146
Andriy
  • 14,781
  • 4
  • 46
  • 50
  • 1
    Would that say what the original value was? – VLAZ Oct 18 '18 at 11:16
  • 1
    Not sure (I will check it later more in depth...), you would save it on change event to element dataset for example – Andriy Oct 18 '18 at 11:21
  • 2
    Thanks! Actually, `valueMissing` is `false` even when the value *is* missing... maybe because the field isn't mandatory. The `badInput` flag works for Chrome and Firefox, but it's not on IE11. So I guess a check like `input.validity.badInput || isNan(input.value)` tells us that there is text, but it's invalid. – Bill Keese Oct 18 '18 at 14:15
  • There is a very similar question (https://stackoverflow.com/questions/18852244/how-to-get-the-raw-value-an-input-type-number-field?noredirect=1&lq=1) with no working solution or hack, but with reasonable explanations – Andriy Oct 20 '18 at 14:03
2

According to the answer to this question, you won't be able to get the value of an input field of type number unless it's a valid numeric input.

On the other hand, you can make the input field of type text instead and validate it with the help of regex like this:

window.onload = ()=>{
  let numBox = document.getElementById('number-box');
  let button = document.getElementById('show-value');
  let pattern = /^\d*(\.\d+)?$/;
  numBox.addEventListener('input', function(){
    if(pattern.test(this.value) && this.value !== ''){
      console.log('valid');
    }
    else {
      console.log('invalid!');
    }
  });
  button.addEventListener('click', ()=>{
    alert(`The current value in the input field is ${numBox.value}`);
  });
};
<input type="text" id="number-box">
<input type="button" id="show-value" value="Show Value">

Also, here's a working example :)

C.RaysOfTheSun
  • 706
  • 1
  • 6
  • 9
0

You can use jquery $.isNumeric() function for numeric validation like the following.

function showInputValue() {
    const inputValue = document.getElementById("numberInput").value;
    //const inputValueAsNumber = 
    //document.getElementById("numberInput").valueAsNumber;

    if(inputValue !== '' && $.isNumeric(inputValue))
       {
         alert("number is ok");
        }
    else if(inputValue  == '')
        {
         alert("input is empty");
        }
   else {
        alert("Number is invalid");
        }
   }
Ali
  • 746
  • 1
  • 7
  • 17
  • 1
    I don't see how that could work, as I said above, `inputValue` will be `""` regardless of whether the `` is actually blank or has a value like "1.2.3". – Bill Keese Oct 18 '18 at 13:41
  • check the updated answer. now it also check if the input is empty. – Ali Oct 18 '18 at 17:09
  • As I said above, this won't work because `inputValue` will be `""` regardless of whether the `` is actually blank or has a value like `"1.2.3"` – Bill Keese Oct 20 '18 at 13:14