Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a user from entering negative values in Html input

Tags:

html

I am using the following html input element for collecting the product quantity in Html page but the user can still go ahead and manually enter negative value. For example: I selected the the textbox and entered -100 and input field took it without complaining about it.

How can I prevent user from entering 0 and non-negative values in Html input element?

<input type="number" id="qty" value="" size="3" min="1" />
like image 578
Nital Avatar asked Nov 30 '22 18:11

Nital


1 Answers

Due to the <input type="number"> still not being widely well supported, you are still better off using a text input. Preventively you could disallow any characters which are not numbers with the keypress event and e.preventDefault(). However be sure that if you want to support legacy browsers (IE8-), there are a number of inconsistencies to take into account regarding returned key codes/ char codes. If you also want to disallow pasting non-number content, you can do so with the paste event and e.clipboardData.getData('plain/text') (for a complete implementation see here)

Test with the code below:

var myInput = document.getElementsByTagName('input')[0];
myInput.addEventListener('keypress', function(e) {
  var key = !isNaN(e.charCode) ? e.charCode : e.keyCode;
  function keyAllowed() {
    var keys = [8,9,13,16,17,18,19,20,27,46,48,49,50,
                51,52,53,54,55,56,57,91,92,93];
    if (key && keys.indexOf(key) === -1)
      return false;
    else
      return true;
  }
  if (!keyAllowed())
    e.preventDefault();
}, false);

// EDIT: Disallow pasting non-number content
myInput.addEventListener('paste', function(e) {
  var pasteData = e.clipboardData.getData('text/plain');
  if (pasteData.match(/[^0-9]/))
    e.preventDefault();
}, false);
<input type="text">
like image 100
webketje Avatar answered Dec 04 '22 11:12

webketje