Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if an <input type=number> is blank vs. has an invalid value?

Tags:

javascript

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>
like image 384
Bill Keese Avatar asked Oct 18 '18 11:10

Bill Keese


People also ask

How do you check entered value is number or not?

isNumeric() method is used to check whether the entered number is numeric or not. $. isNumeric() method: It is used to check whether the given argument is a numeric value or not. If it is numeric then it returns true Otherwise returns false.

How check field is empty or not in Javascript?

Use the condition with “” and NULL to check if value is empty. Throw a message whenever ua ser does not fill the text box value.


1 Answers

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.

like image 91
Andriy Avatar answered Sep 18 '22 22:09

Andriy