Close
Do you want more articles like this delivered straight to your inbox?

Subscribe now to my e-mail newsletter and get my latest articles and project updates delivered directly to your inbox. Never miss an update.

How to allow only positive integers in HTML number input elements

Published March 30, 2021; last updated on April 6, 2021
How to allow only positive integers in HTML number input elements

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))">

Conclusion

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! ✌️👇

Stay up to date with all things Laravel, Tailwind, WordPress & PHP

Subscribe now to my e-mail newsletter and get my latest articles and project updates delivered directly to your inbox. Never miss an update.

Image Ralph J. Smit
Ralph is a designer gone developer. He happily lives in the Netherlands. His passion for good design drove him towards development, because he felt that no-code tools were too limiting. On this blog, Ralph writes the articles he would've wanted to have during his continual developer journey. → Follow on Twitter

Comments

Leave a reply

Your email address will not be published. Required fields are marked *