Prevent negative inputs in form input type="number"?
Asked Answered
M

10

65

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?

Mandler answered 22/7, 2015 at 23:3 Comment(5)
In HTML 5 u can do like this: <input type="number" name="quantity" min="0"> and I think this is the most elegant way to restrict user input to positive numbers without writing a validation function.Paraffinic
@GoodBadandUgly — That was mentioned in the question, along with its limitations.Ouachita
Be aware that users can always bypass such limitations! If you submit anything to server-side (read db or data fetch functions) you have to validate once again anyway.Stalker
Why do you want to block the user without showing him an error message ? If the user tries to enter -10, you give him a 10 which is totally different and he might not even notice you changed his intent (users look at the keyboard while typing). What is the rationale in this ?! I wish developers would stop doing that.Burgwell
Set pattern="[1-9][0-9]*". Change the [1-9] to [1-9]? if you don't require any input.Bedouin
D
140

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>
Delija answered 22/7, 2015 at 23:48 Comment(6)
Really awesome! it only allows the numbers which are between Min an Max, Instead of writing javascript code as others suggested, its better to go with this oninput="validity.valid||(value='');"Tact
The only problem with this solution is it completely clears the previously entered value when an invalid value is entered.Sacrifice
How can we prevent the entering of the offending key and not clearing the entire field?Beane
You can could use something like <input type="number" name="test" min=0 save="" oninput="validity.valid ? this.save = value : value = this.save;"> Obviously, this shouldn't be used as is... You should write your own handler function that checks validity.valid and does the right thing.Delija
Is there a way to convert this to a reusable function and then attach it via addEventListener? (I am using React actually) would prefer a reusable function.Grantinaid
The Demo works great, but Im using it on React on a Input element and I still can type the "-" symbol.Tomkins
C
33

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.

Castello answered 22/7, 2015 at 23:36 Comment(0)
C
8

If you want to ensure default value, i.e min value, or any other value, this is working solution. This is also preventing to clear the input field. Same way you can set to it's max value as well.

<input type="number" min="1" max="9999" maxlength="4" oninput="this.value=this.value.slice(0,this.maxLength||1/1);this.value=(this.value   < 1) ? (1/1) : this.value;">
Collie answered 9/11, 2016 at 7:11 Comment(1)
> "This is also preventing to clear the input field" No. This clears the input and fills the minimum. Not clears - when you type 123- and see 123 in the field.Spirituality
E
3

The following script will only allow numbers or a backspace to be entered into the input.

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

number.onkeydown = function(e) {
    if(!((e.keyCode > 95 && e.keyCode < 106)
      || (e.keyCode > 47 && e.keyCode < 58) 
      || e.keyCode == 8)) {
        return false;
    }
}
<input type="number" id="number" min="0">
Embarrassment answered 22/7, 2015 at 23:21 Comment(1)
This is too restrictive as it does not allow the user to tab out of the field - extremely important for fast data input apps or assistive technologies (eg people who cannot use a mouse tab into the field and then they are stuck)Doubletalk
N
2

WAY 01:

Template:

<input name="price" type="number" (keydown)="onKeydown($event)" min="0" required />

file-name.ts:

onKeydown(event: KeyboardEvent): boolean {
    if (!((event.keyCode > 95 && event.keyCode < 106)
      || (event.keyCode > 47 && event.keyCode < 58)
      || event.keyCode === 8)) {
        return false;
    }
    return true;
  }

WAY 02:

Template:

<input name="price" type="number" min="0" oninput="this.value = Math.abs(this.value)" required />
Nissensohn answered 9/7, 2020 at 9:35 Comment(1)
abs is not correct as it just flips the value to absolute. The correct way is to use max with 0 as a second argumentCongeries
S
1

type="number" already solves allowing numbers only to be typed as the other answers here point out.

Just for reference: with jQuery you can overwrite negative values on focusout with the following code:

$(document).ready(function(){
    $("body").delegate('#myInputNumber', 'focusout', function(){
        if($(this).val() < 0){
            $(this).val('0');
        }
    });
});

This does not replace server side validation!

Stalker answered 3/10, 2016 at 17:50 Comment(0)
G
1

On html put onKeypress event listener

<input type="text" onkeypress="validate(event)">

write the validate function like this:

<script>
    function validate(event) {
      if (event.key == "-") {
        event.preventDefault();
        return false;
      }
    }    
</script>

in case of angularjs pass $event in place of event, i have tested this in angularjs and in javascript

Ghee answered 25/6, 2020 at 8:30 Comment(0)
R
0

In HTML5, I like this way. Also it's much suitable with angular.

<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
Rayshell answered 11/11, 2019 at 10:40 Comment(1)
Why would you do that ? This is not what I typed... if I wanted to type -3, then why do you convert it to 3 ? what is the rationale ?! This makes absolutely no sense.Burgwell
N
0

Angular | Typescript Syntax

HTML:

<input type="number" (keydown)="onKeyDown($event)">

ts File:

  onKeyDown(e:any):void{
        if(!e)
          return;
       console.log('ee',e);
       if((e.code==='Minus' && e.keyCode==189 && e.key==='-') ||  (e.keyCode==187 && e.key==='+') 
      ||(e.code==='KeyE' && e.keyCode==69 && e.key==='e')){
        e.preventDefault();
       }
      }

JavaScript Syntax

<html>

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

   
</head>

<body>
    <div class="container">
        <h1>Create Account</h1>
        <form id="user" name="user">
            <div class="row">
                <div class="col-6">
                    <label for="fname">First Name*</label>
                    <input type="number" id="fname" placeholder="Enter Your first name" required>
            </div>
            
    </div>
    </form>
    </div>
</body>

</html>

<script>

    $('#fname').keydown(function(e){         
        console.log('evt e.key:::::', e);
        if(e.key=='-' && e.keyCode==189 || e.key=='+' && e.keyCode==187 )
          {
            e.preventDefault();
          }
        console.log('evt e.keyCode:::::', e.keyCode);
        console.log('evt e.code:::::', e.code);

    });
  
</script>
Nightingale answered 24/4, 2022 at 18:56 Comment(0)
V
0

You can use both onfocusout and onkeypress to prevent bad characters like minus, exponential, etc and validate the results only after the user completes entering the data. This would allow for a positive floating number. I have answered it in detail here -

function positiveDecimalInputValidate(e) {
  if (e.value == "") {
    e.value = "";
    return
  }
  const newVal = Math.abs(e.value);
  if (newVal != e.value) {
    e.value = newVal;
  }
}

function badCharForNumberInputValidate(event) {
  const badKeys = ['-', '+', 'e', 'E', ','];
  if (badKeys.includes(event.key)) {
    event.preventDefault();
  }
}
<input type="number" onfocusout="positiveDecimalInputValidate(this);" onkeypress="badCharForNumberInputValidate(event)">
Vaden answered 16/3, 2024 at 11:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.