Prevent negative value from being entered in HTML input type number field?


While creating HTML5 input type number in the html form, I would like to disable or prevent user from entering negative number in it, user should be able to enter only positive number, how can i do that, current HTML code is as below

<input type="number" id="Price" name= "Price" />

 


Asked by:- jon
2
: 16048 At:- 10/4/2018 12:21:32 PM
HTML html5 form html number selector







2 Answers
profileImage Answered by:- jaiprakash

The simplest solution is to use HTML like below

<input type="number" min="0" id="Price" name= "Price">

The above code will help you but not completely, so you would have add Javascript, to prevent user from being entering a negative value using the keyboard

var number = document.getElementById('number');

// Listen for input event on numInput.
number.onkeydown = function(e) {
    if(!((e.keyCode > 95 && e.keyCode < 106)
      || (e.keyCode > 47 && e.keyCode < 58) 
      || e.keyCode == 8)) {
        return false;
    }
}

Here is the full fiddle example.

OR

Simply use below HTML, with in-line Javascript, which will allow 0 or greater tha 0 value.

<input type="number" min="0" oninput="this.value = 
 !!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
2
At:- 10/7/2018 6:40:01 PM Updated at:- 9/27/2022 7:39:08 AM
thanks, it works. 0
By : jon - at :- 10/8/2018 5:07:51 PM


profileImage Answered by:- bhanu

If you want to enter float in the input type and prevent negative value, you can use below code

<input type="number" min="0.01" step="0.01">

OR 

You can also use onKeyup event, which will convert negative number into positive.

<input type="number" onkeyup="if(this.value<0){this.value= this.value * -1}">
1
At:- 5/20/2021 11:53:50 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use