How to use a pattern on an input[type=“number”]?

守給你的承諾、 提交于 2020-06-23 07:46:29

问题


I want the default value to be 0 and recolor the input if it's more than 0, using :valid. Am I doing something wrong? Is Google Chrome wrong? Or the HTML5 specification? I want to solve this without JS.

:valid {
  background: green
}
<p>This should not be green, but it is:</p>
<input max="100" min="0" pattern="^[1-9]\d*$" type="number" value="0" />

<p>Works perfectly, if the type is changed to text:</p>
<input pattern="^[1-9]\d*$" type="text" value="0" />

回答1:


Citing MDN on the pattern property (highlighting added):

pattern

A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.

Interestingly I can't find any mentioning of that in both W3C and WhatWG standards.




回答2:


I see that if you give the minimum value of 1, the color is not green for 0. The color changes to green when you enter 1. I think that is what you are expecting, right?

Basically, you can use min and max values for validation purpose. I don't think you need pattern for this.

<input max="100" min="1" type="number" value="0" />

There is one limitation here. If you leave the field empty, it is still green!



来源:https://stackoverflow.com/questions/33411753/how-to-use-a-pattern-on-an-inputtype-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!