What an input type=number really accepts: a quick test
<input type="number"> looks like it only takes numbers. In practice it takes some strings you might not expect and silently drops others. I ran the cases below in Chrome 155 in a scratch input, and checked the rules agai
<input type="number"> looks like it only takes numbers. In practice it takes some strings you might not expect and silently drops others. I ran the cases below in Chrome 155 in a scratch input, and checked the rules against the HTML spec and MDN.
What I set, and what came back
const i = document.createElement("input");
i.type = "number";
i.value = "1e3"; // i.value: "1e3" valueAsNumber: 1000
| Value set |
value afterwards |
valueAsNumber |
|---|---|---|
"12" |
"12" |
12 |
"-5" |
"-5" |
-5 |
"1.5" |
"1.5" |
1.5 |
"1e3" |
"1e3" |
1000 |
"abc" |
"" |
NaN |
"1,5" |
"" |
NaN |
" 7" (leading space) |
"" |
NaN |
"0x10" |
"" |
NaN |
"1e" |
"" |
NaN |
Two things stand out. First, "1e3" is accepted and stays as typed, so a field that someone fills by hand can hold exponent notation. Second, a comma decimal like "1,5" is not a number to this property. It becomes an empty string with no error.
I also set maxLength = 3 and then value = "123456". The value stayed "123456". The spec's table of which attributes apply to which input type lists maxlength for text, search, telephone, URL, email and password inputs, and not for number. If you need a length limit on digits, use min and max for the range, or a text input with inputmode="numeric" and your own check.
For step, I set step="0.01" and tried 0.1 (valid) and 0.105 (validity.stepMismatch was true).
Why this bites in forms
- Reading
input.valuegives you a string, and it is""both when the box is empty and when the user typed something the browser rejected. You cannot tell the two apart fromvaluealone. - MDN also notes that number inputs are a poor fit for things that are only made of digits, such as postal codes or card numbers, because they are not really numbers. A leading zero is a good example of what you lose.
A cheap test list
- Type
1e3and check what your code does with"1e3". - Type
1,5and see whether your form shows an error or just treats the field as empty. - Set a leading space or paste
0x10. - Check
validity.badInputon a value the user typed, not one set from script. I only tested script-set values here, so I can't say how real typing behaves across browsers. - Try a value that fails
step.
What do you do when a number field comes back empty?htmlwebdev
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.