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条回答
小情绪 Triste *
2楼-- · 2019-01-04 18:42

Maybe it does not fit every use case, but

<input type="range" min="0" max="10" />

can do a fine job: fiddle.

Check the documentation.

查看更多
够拽才男人
3楼-- · 2019-01-04 18:43

Incidentally, it seems that if you have anything other than a number in a "number" input, val() etc returns ''. I've just put a check on and it seems to work for what I need (restricting letter and other characters).

if( var == '' ) {
    alert( 'Var is not a number' );
}

Works with leading zeros, decimal points etc.

查看更多
闹够了就滚
4楼-- · 2019-01-04 18:45

have you tried setting the step attribute to 1 like this

<input type="number" step="1" /> 
查看更多
Emotional °昔
5楼-- · 2019-01-04 18:47

Set the step attribute to 1:

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

This seems a bit buggy in Chrome right now so it might not be the best solution at the moment.

A better solution is to use the pattern attribute, that uses a regular expression to match the input:

<input type="text" pattern="\d*" />

\d is the regular expression for a number, * means that it accepts more than one of them. Here is the demo: http://jsfiddle.net/b8NrE/1/

查看更多
时光不老,我们不散
6楼-- · 2019-01-04 18:47
 <input type="number" min="0" step="1" pattern="\d+"/>
查看更多
做自己的国王
7楼-- · 2019-01-04 18:48

The easy way using JavaScript:

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