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>
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With