How to allow only positive integers in HTML number input elements | RJS

How to allow only positive integers in HTML number input elements

Ralph J. Smit Laravel & PHP-developer.

I recently found myself in the situation where I was using an HTML number input element, but where I wanted to only accept positive numbers. That might seem like an easy task, but it turned out that it was quite complicated and that you needed to sprinkle in a little bit of JavaScript. In this article, I'll show you how to only allow positive number input.

Let's start with a simple HTML input element. This element is just an input element and nothing more. As you see, you can still

  1. type negative and positive numbers;

  2. use the arrows to get both positive and negative numbers

<input type="number">

The HTML input `min` attribute

Well, it turns out that the <input> element can have a special attribute: the min attribute. Problem solved, isn't it? Well, it turns out that we here only have one part of the solution.

Try out the Codepen:

<input type="number" min="0">

As you see, it's now not possible anymore to add negative numbers with the arrows. But you still can type both negative and positive numbers. How to fix this?

Add a little bit of JavaScript to disable negative number typing

To disallow the typing of negative numbers, we need to add the onkeypress attribute and use a little bit of JavaScript here. You can directly place this in the HTML, so it's very lightweight.

Every time a key is clicked, the JavaScript checks whether it's a number and whether it's positive. Try typing a negative number now!

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


As you've seen, to only allow positive integers (whole numbers), you can combine the use of the min attribute and the onkeypress attribute with a little bit of JavaScript.

Have you used this yourself or have you got a better hack? Let me know in the comments! βœŒοΈπŸ‘‡

Published by Ralph J. Smit on in Guides. Last updated on 10 March 2022.

Like what you read?

Get notified when I publish something new, and unsubscribe at any time.