SCS SCS - 7 months ago 11
HTML Question

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

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>

Answer

To diallow any input but numeric, you may use

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

See demo

Here, the event.charCode == 8 || event.charCode == 0 condition handles the case when DELETE or BACKSPACE keys are pressed (important for Firefox, see Mohit's comment below).

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.

Comments