简体   繁体   中英

Chrome/HTML5: Input type number not respecting max attribute?

I have the following markup:

<input type="number" max="99" />

In Google Chrome (and possibly other webkit browsers), this will restrict the spinner's up arrow from going over 99, but it does not prevent the user from typing a number higher than 99. Even onblur, the invalid value is not removed/replaced or even a warning given that the value is invalid.

Am I misinterpreting how it's supposed to work, or is this a bug? I am using the latest version of Chrome (19 at the time of writing).

Edit:

To clarify, I want to know why a number greater than the specified max is allowed to be input in the first place. I realize that it gives a tooltip on form submission telling you that it's invalid, but it seems like inconsistent behavior that the spinner will not allow you to go above the max, yet you can simply type a number above the max at any time to circumvent it.

If this is desired behavior for some reason, why is that? And is there a better option to enforcing the input range without resorting to JS?

It does work but you only see an error message (tooltip) if you put a submit button and a form into your code:

<form action="#" method="get">
  <input type="number" max="99" />
  <input type="submit" value="Submit!" />
</form>

jsFiddle

It's an old question, but I didn't find any relevant answers for this question anywhere. this behaviour is still around in chrome (version 61).

I have found a little trick that can be used in some situation. it's relevant for those who use data-binding libraries like aurelia , angular etc.. I tested only on aurelia - but that should work also for others.

the trick relies on the fact that input of type range enforce the min / max constraints.

we simply create another input (of type range ) that is bounded to the same value as the regular input, and we hide it via css .

when the user inputs something that is greater than the max value, it will snap back to the max value.

here's a demo in aurelia: https://gist.run/?id=86fc278d3837718be4691acd5625aaad

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM