HTML5: number input type that takes only integers?

2019-01-04 17:48发布

I'm using the jQuery Tools Validator which implements HTML5 validations through jQuery. It's been working great so far except for one thing. In the HTML5 specification, the input type "number" can have both integers and floating point numbers. This seems incredibly short-sighted since it will only be a useful validator when your database fields are signed floating point numbers (for unsigned ints you'll have to fall back to "pattern" validation and thus loose extra features like the up and down arrows for browsers that support it). Is there another input type or perhaps an attribute that would restrict the input to just unsigned integers? I couldn't find any, thanks.

EDIT

Ok guys, I appreciate your time and help, but I see many undeserved up-voting going on :D. Setting the step to 1 is not the answer since it doesn't restrict the input. You can still type a negative floating point number into the textbox. Also, I am aware of pattern validation (I mentioned it in my original post), but that was not part of the question. I wanted to know if HTML5 allowed restricting an input of type "number" to positive integer values. To this question the answer, it seems, would be "no, it does not". I didn't want to use pattern validation because this causes some drawbacks when using jQuery Tools validation, but it now seems that the specification doesn't allow for a cleaner way to do this.

20条回答
唯我独甜
2楼-- · 2019-01-04 18:27

Yes, HTML5 does. Try this code (w3school):

<!DOCTYPE html>
<html>
<body>

<form action="">
  Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5" />
  <input type="submit" />
</form>

</body>
</html>

See the min and max paremeter? I tried it using Chrome 19 (worked) and Firefox 12 (did not work).

查看更多
Ridiculous、
3楼-- · 2019-01-04 18:28

https://www.w3.org/wiki/HTML/Elements/input/number

The best you can achieve with HTML only

    <input type="number" min="0" step="1"/>

查看更多
我命由我不由天
4楼-- · 2019-01-04 18:29

This is not only for html5 all browser is working fine . try this

onkeyup="this.value=this.value.replace(/[^0-9]/g,'');"
查看更多
欢心
5楼-- · 2019-01-04 18:30

Just putting it in your input field : onkeypress='return event.charCode >= 48 && event.charCode <= 57'

查看更多
别忘想泡老子
6楼-- · 2019-01-04 18:32

Pattern are always preferable for restriction, try oninput and min occur 1 for inputting only numbers from 1 onwards

<input type="text" min="1" oninput="this.value=this.value.replace(/[^0-9]/g,'');"
                                value=${var} >
查看更多
登录 后发表回答