HTML input for Positive Whole Numbers Only (Type=number)

98,186

Solution 1

To disallow any input but numeric, you may use

<input type="text" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" name="itemConsumption" />
                   ^------------....

<form id="mfrm">
<table>
    <tr>
        <td>Enter number only: <input type="text" name="itemConsumption" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" /></td>
        <td><input type="Submit"/></td>
    </tr>
</table>

Here, the event.charCode == 8 || event.charCode == 0 || event.charCode == 13 condition handles the case when DELETE, BACKSPACE or ENTER keys are pressed (important for Firefox, see Mohit's comment below and datashaman's comment related to enabling the ENTER key).

The event.charCode >= 48 && event.charCode <= 57 means that only 0 (decimal code 48) and all other digits up to 9 (decimal code 57) will be returned.

Solution 2

You can use type, min and oninput

<input type="number" min="0" step="1" oninput="validity.valid||(value='');">

<form>
<label>Input with positive numbers only</label><br/><br/>
<input type="number" min="0" step="1" oninput="validity.valid||(value='');">
</form>

Solution 3

To allow only number values you can use as follows:

<td><input type="number" pattern="\d+" name="itemConsumption" /></td>

Solution 4

I tried a lot of different solutions to achieve this, and I finally came up with this one, which does the job perfectly for us. It works for typing and for copy/paste, and I couldn't find any unwanted side-effects.

<form>
    <input
        type="number"
        min="0"
        step="1"
        onfocus="this.previousValue = this.value"
        onkeydown="this.previousValue = this.value"
        oninput="validity.valid || (value = this.previousValue)"
    />
</form>

It is like Nikhil Mahirrao's solution, but it will cause invalid keystrokes to be simply ignored without emptying the input.

Solution 5

If it comes to HTML5 then you might try min attribute:

<input type="number" min="0">
Share:
98,186
SCS
Author by

SCS

Updated on January 05, 2022

Comments

  • SCS
    SCS over 2 years

    I can't find the right regex pattern for this, even though there are a lot of questions in this kind.

    I dont want the user to be able to type or input

    <td><input type="number" pattern=" 0+\.[0-9]*[1-9][0-9]*$" name="itemConsumption" /></td>
    
    1. -1.0 (Negative values)
    2. String Values and any character
    3. 1.0 (Decimal Values)
    4. No range Limit

    I only want to accept positive whole numbers

    SOLVED no need for regex, I did not know this :D

    <td><input type="number" pattern=" 0+\.[0-9]*[1-9][0-9]*$" name="itemConsumption" onkeypress="return event.charCode >= 48 && event.charCode <= 57"</td>