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
0
: 60 At:- 10/4/2018 12:21:32 PM
HTML html5 form html number selector






1 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.

2
At:- 10/7/2018 6:40:01 PM
thanks, it works. 0
By : jon - at :- 10/8/2018 5:07:51 PM





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