Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>  
like image 491
SCS Avatar asked Sep 25 '15 07:09

SCS


People also ask

How do you input only positive numbers in HTML?

As we know, the <input type="number"> specifies a field for entering a number. If you want to restrict the <input> field to only positive numbers, you can use the min attribute.

How do you make an input type number only?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do I restrict input fields with only numbers?

To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.


1 Answers

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.

like image 164
Wiktor Stribiżew Avatar answered Sep 19 '22 10:09

Wiktor Stribiżew