Reputation: 894
The below code in Chrome isn't enforcing the pattern of '00.00', it is allowing any format of number with unlimited decimals. The pattern works fine when using input type 'text' so not sure if this is a 'number' problem ?
Any suggestions appreciated.
<input type="number" step="1.00" min="0" pattern="\d+(\.\d{2})?" class="form-control" id="JobCost" name="jobcost">
Upvotes: 35
Views: 24092
Reputation: 1033
This is a fairly old question, but I was trying to understand the same thing and this is what I was able to determine.
First, input of type number
does not use the pattern
attribute, so it ignores it.
Second, the step
attribute not only determines the step of the up/down clicker, but also the set of valid values. For example, if you set the step at 1.11, the valid values are 1.11, 2.22, 3.33 and so on. If you enter 5.2 and submit, it will respond with "Please enter a valid value. The two nearest valid values are 4.44 and 5.55." If you do not enter the step, it defaults to 1. Then it only allows "integers" (I use quotes because technically it will allow 1.
or 1.0
or 1.00
, etc.). If you want to use any number, use step="any"
. I did read somewhere that while chrome enforces the default step of 1, firefox will allow decimals (treats it as any??).
Third, none of this works if it's not embedded within a form
tag.
So if you want to enforce a number to 2 decimals, either use type="number" step=".01"
(understanding that your up/down clicker will increase/decrease by .01) or use type="text" pattern="\d+(\.\d{2})?"
. Note that on your regex, it will not allow .23
since you have \d+
. It will allow 0.23
though. If you want to allow a decimal without a leading 0, use \d+(\.\d{2})?
instead. It also only allows 2 decimal places or none (rejects 1.
and 1.2
but accepts 1.20
). If that's what you want, great. Just wanted to make sure.
\d*(\.\d{0,2})?
would accept any number down to 2 decimal points but not more. It would also accept just .
though, so you'd have to play around based on what you want.
Upvotes: 97