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>