html5 input type pattern,html - HTML5 Input Type 'Number' Pattern not being enforced - Stack Overflo...

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.

Hope that helps you or anyone else that comes across this like I did.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值