[html] How to make type="number" to positive numbers only

currently I have the following code

<input type="number" />

it comes out to something like this

enter image description here

The little selector things on the right allow the number to go into negative. How do I prevent that?

I am having doubts about using type="number", it is causing more problems than it is solving, I am going to sanity check it anyways, so should I just go back to using type="text"?

This question is related to html

The answer is


If you try to enter a negative number, the onkeyup event blocks this and if you use the arrow on the input number, the onblur event resolves that part.

_x000D_
_x000D_
<input type="number" _x000D_
    onkeyup="if(this.value<0)this.value=1"_x000D_
    onblur="if(this.value<0)this.value=1"_x000D_
>
_x000D_
_x000D_
_x000D_


Try this:

  • Tested in Angular 8
  • values are positive
  • This code also handels null and negitive values.
              <input
                type="number"
                min="0"
                (input)="funcCall()" -- Optional
                oninput="value == '' ? value = 0 : value < 0 ? value = value * -1 : false"
                formControlName="RateQty"
                [(value)]="some.variable" -- Optional
              />

add this code in your input type;

onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57"

for example:

<input type="text" name="age" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />

You can force the input to contain only positive integer by adding onkeypress within the input tag.

_x000D_
_x000D_
<input type="number" onkeypress="return event.charCode >= 48" min="1" >
_x000D_
_x000D_
_x000D_

Here, event.charCode >= 48 ensures that only numbers greater than or equal to 0 are returned, while the min tag ensures that you can come to a minimum of 1 by scrolling within the input bar.


Try this:

Yii2 : Validation rule 

    public function rules() {
    return [
['location_id', 'compare', 'compareValue' => 0', 'operator' => '>'],
        ];
}

I have found another solution to prevent negative number.

<input type="number" name="test_name" min="0" oninput="validity.valid||(value='');">

It depends on how precise you want to be. It you want to accept only integers, than:

_x000D_
_x000D_
<input type="number" min="1" step="1">
_x000D_
_x000D_
_x000D_

If you want floats with, for example, two digits after decimal point:

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


I cannot find the perfect solution as some work for inputting but not for copy&paste, some are the other way around. This solution works for me. It prevents from negative number, typing "e", copy&paste "e" text.

create a function.

<script language="JavaScript">

  // this prevents from typing non-number text, including "e".
  function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    let charCode = (evt.which) ? evt.which : evt.keyCode;
    if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
      evt.preventDefault();
    } else {
      return true;
    }
  }
</script>

add these properties to input. this two prevent from copy&paste non-number text, including "e". you need to have both together to take effect.

<input type="number" oninput="validity.valid||(value='');" onpress="isNumber(event)" />

If you are using Vue you can refer this answer here. I have extracted it to a mixin which can be reused.


You can use the following to make type="number" accept positive numbers only:

input type="number" step="1" pattern="\d+"

You can turn negative input into a positive number by the following:

_x000D_
_x000D_
<input type="number" onkeyup="if(this.value<0){this.value= this.value * -1}">
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
<input type="number" min="1" step="1">
_x000D_
_x000D_
_x000D_


If needing text input, the pattern works also

<input type="text" pattern="\d+">

_x000D_
_x000D_
(function ($) {
  $.fn.inputFilter = function (inputFilter) {
    return this.on('input keydown keyup mousedown mouseup select contextmenu drop', function () {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty('oldValue')) {
        this.value = this.oldValue;
        //this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        this.value = '';
      }
    });
  };
})(jQuery);

$('.positive_int').inputFilter(function (value) {
  return /^\d*[.]?\d{0,2}$/.test(value);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="positive_int"/>
_x000D_
_x000D_
_x000D_

Above code works fine for all !!! And it will also prevent inserting more than 2 decimal points. And if you don't need this just remove\d{0,2} or if need more limited decimal point just change number 2


With text type of input you can use this for a better validation,

return (event.keyCode? (event.keyCode == 69 ? false : event.keyCode >= 48 && event.keyCode <= 57) : (event.charCode >= 48 && event.charCode <= 57))? true : event.preventDefault();

Try

<input type="number" pattern="^[0-9]" title='Only Number' min="1" step="1">


It depends on whether you want an int or float field. Here's what the two would look like:

<input type="number" name="int-field" id="int-field" placeholder="positive int" min="1" step="1">
<input type="number" name="float-field" id="float-field" placeholder="positive float" min="0">

The int field has the correct validation attached to it, since its min is 1. The float field accepts 0, however; to deal with this, you can add one more constraint validator:

function checkIsPositive(e) {
  const value = parseFloat(e.target.value);
  if (e.target.value === "" || value > 0) {
    e.target.setCustomValidity("");
  } else {
    e.target.setCustomValidity("Please select a value that is greater than 0.");
  }
}

document.getElementById("float-field").addEventListener("input", checkIsPositive, false);

JSFiddle here.

Note that none of these solutions completely prevent the user from trying to type in invalid input, but you can call checkValidity or reportValidity to figure out whether the user has typed in valid input.

Of course, you should still have server-side validation because the user can always ignore client-side validation.


Other solution is to use Js to make it positive (min option can be disabled and is not valid when the user types smth) The negative if is not necessary and on('keydown') event can also be used!

let $numberInput =  $('#whatEverId');
$numberInput.on('change', function(){
    let numberInputText = $numberInput.val();
    if(numberInputText.includes('-')){
        $numberInput.val(Math.abs($numberInput.val()));
    }
});