Reputation: 1931
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>
Upvotes: 10
Views: 2303
Reputation: 776
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");
}
}
Upvotes: 0
Reputation: 15442
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.
Upvotes: 8
Reputation: 716
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 :)
Upvotes: 2