35

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">

JSFiddle

1
  • ^\d+(\.\d{1,2})?$ Commented Jan 19, 2018 at 18:05

1 Answer 1

97

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Great explanation. I got the message "Please enter a valid value. The two nearest valid values are 4.44 and 5.55." like you stated, but did not know why. I was working on prices so any decimals are allowed. When I set step: :any (Rails) everything worked fine.
Point 3 is no longer accurate for Chrome (I have Version 75.0.3770.100 (Official Build) (64-bit)). The warnings appear even while outside of a form tag.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.