Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number input type that takes only integers?

People also ask

How do I allow only input integers?

The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.

How do you only input integers in python?

As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function.

What is the input type for numbers?

The <input type="number"> defines a field for entering a number. Use the following attributes to specify restrictions: max - specifies the maximum value allowed.

How do you validate a number in input?

A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the required attribute is used, the input is no longer considered valid when empty. Note: Any number is an acceptable value, as long as it is a valid floating point number (that is, not NaN or Infinity).


The best you can achieve with HTML only (documentation):

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

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.


<input type="text" name="PhoneNumber" pattern="[0-9]{10}" title="Phone number">

Using this code, the input to the text field limits to enter only digits. Pattern is the new attribute available in HTML 5.

Pattern attribute doc


The easy way using JavaScript:

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >

Pattern is nice but if you want to restrict the input to numbers only with type="text", you can use oninput and a regex as below:

<input type="text" oninput="this.value=this.value.replace(/[^0-9]/g,'');" id="myId"/>

I warks for me :)