Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between NaN input and empty input with an Input of type="number"

I want to use a form input with type="number" and only allow numbers to be entered.

<input type="number" class="form-control fc-input"/>

I don't have a submit button, instead the value is checked after the input loses focus. However when you use type="number" and a non-number is entered, both the valueAsNumber and the value attributes of the input will be useless (NaN respectively ""). The problem with this is that I want to differentiate between the user entering an empty string (""), and the user entering a non-number value (e.g. 123abc). When the input is empty I want to execute function a, and if it's just a non-number I want to execute function b (otherwise do c).

Is there a good way to differentiate between NaN input and empty ("") input like this?

like image 979
usealbarazer Avatar asked Dec 25 '22 02:12

usealbarazer


1 Answers

The problem is input type of number does a lot of stuff under the covers and the specification for it does not expose the actual invalid value to you. So an empty input and an invalid string look the same. So you need to do some investigation work using validity

var result = document.getElementById("result");

document.getElementById("num").addEventListener("keyup", function() {
  var isValid = this.validity.valid;
  var len = this.value.length;

  if (isValid && !len) {
      result.innerHTML = "No value";
  } else if (!isValid) {
      result.innerHTML = "Invalid number";
  } else {
      result.innerHTML = "Valid number: " + this.valueAsNumber;
  }

});
<input type="number" id="num" />
<span id="result"></span>

Problem with the code above is if you make it required, the empty check will fail. If it is required the if check would need to be

if (!isValid && this.validity.valueMissing) {
like image 188
epascarello Avatar answered May 18 '23 22:05

epascarello