How to Allow Only Positive Numbers in the Input Number Type

Solutions with HTML attributes

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.

Example of allowing only positive numbers:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <input type="number" min="0" value="10">
  </body>
</html>

Result

As you can see in the example above, using only the min attribute works for the selector arrows, and you can still type a negative number.

To restrict the negative numbers for the arrows, as well as not allow negative typing numbers, try the following.

Example of restricting the typing of negative numbers:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <input type="number" name="test_name" min="0" oninput="validity.valid||(value='');">
  </body>
</html>

And here's the result:

Wait a minute, but how could we achieve that ?

Here we used oninput event, which will validate the input based on our criteria (the minimum number should be at least 0, and we don't like to have any negative numbers!).

As you know, events in JavaScript is executed when something specific, like clicking, typing in an input, etc, happens.

The user enters a value. If it's true validity.value, it will be populated on the input, OR it'll be false, and the input will be blank value="".

A Problem!

Maybe you've noticed, as of now, we still can write float positive numbers like 1.12, but as soon as typing it, the numbers after a period will be replaced by an empty string (Remember our condition of value="").

Try to type 1.23 or any number like that to see what we're talking about!

We want clean positive integer numbers in our input! Here we go!

Let's change our code a little bit and then figure out what's going on:

<input type="number" min="0" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))">

The code above checks with every input the user tries to put in to be only numeric and positive simultaneously.

Also note that theevent.charCode >= 48 && event.charCode <= 57 means that we only want positive integer numbers from 0 to 9.

We've got help from the onkeypress event this time.

The onkeypress event will be fired when the user presses a key on the keyboard.

We specified to have only some special keyboard keys to be able to populate our input, and we've returned them from our onkeypress functionality. charCode property of browser event helped us with that. (Each key of the keyboard has a unique charCode to determine from).

Now you can be sure that your user can only type positive integer numbers in the input!