Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent negative inputs in form input type="number"?

I want to restrict user input to positive numbers in an html form.

I know you can set min="0", however it is possible to bypass this by manually entering a negative number.

Is there any other way to solve this without writing a validation function?

like image 727
Ali Avatar asked Jul 22 '15 23:07

Ali


People also ask

How do you stop negative values in input type numbers?

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

Does input type number allow negative?

The number input type can accept both positive and negative integers as well as floating point numbers.

How do you allow only positive numbers in the input number?

As we know, the <input type="number"> specifies a field for entering a number. If you want to restrict the <input> field to only positive numbers, you can use the min attribute.


2 Answers

This uses Javascript, but you don't have to write your own validation routine. Instead just check the validity.valid property. This will be true if and only if the input falls within the range.

<html>  <body>  <form action="#">    <input type="number" name="test" min=0 oninput="validity.valid||(value='');"><br>    <input type="submit" value="Submit">  </form>  </body>  </html>
like image 72
Mikel Rychliski Avatar answered Sep 20 '22 15:09

Mikel Rychliski


This is not possible without validating the value of the input.

input type=number

The input element with a type attribute whose value is "number" represents a precise control for setting the element’s value to a string representing a number.

Since it is a string representing the number there is no way to be sure that string may be representing numeric values or not.

The Permitted attributes will not give you the ability to validate the value of the number input control.

One way to do this with the help of JavaScript could look like this.

// Select your input element.  var numInput = document.querySelector('input');    // Listen for input event on numInput.  numInput.addEventListener('input', function(){      // Let's match only digits.      var num = this.value.match(/^\d+$/);      if (num === null) {          // If we have no match, value will be empty.          this.value = "";      }  }, false)
<input type="number" min="0" />

If you are planing on sending your data to a server make sure to validate the data on the server as well. Client side JavaScript can not ensure that the data that is being sent will be what you expect it to be.

like image 29
DavidDomain Avatar answered Sep 19 '22 15:09

DavidDomain