How to make type="number" to positive numbers only

Html

Html Problem Overview


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"?

Html Solutions


Solution 1 - Html

Add a min attribute

<input type="number" min="0">

Solution 2 - Html

I have found another solution to prevent negative number.

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

Solution 3 - Html

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

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

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

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

Solution 4 - Html

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

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.

Solution 5 - Html

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

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

Solution 6 - Html

Try

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

Solution 7 - Html

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

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

Solution 8 - Html

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.

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

Solution 9 - Html

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.

Solution 10 - Html

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" />

Solution 11 - Html

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()));
    }
});

Solution 12 - Html

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.

Solution 13 - Html

If needing text input, the pattern works also

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

Solution 14 - Html

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
              />

Solution 15 - Html

This solution might seem a little bit redundant, but takes care of every aspect.

In the form use this

<input type="number" min="0" (keypress)="onlyDigits($event)" >

and in the .ts define the function

onlyDigits(event) {
   let code = event.charCode;
   return (code >= 48 && code <= 57);
}

This ensures only positive numbers might be entered with the arrows. It also prevents typing of any non-digit char (including '-', '+' and 'e')

Solution 16 - Html

I think using type text is best instead of number because using type=number, you will face some problems like arrow keys in input field and value change on up and down key.


<input type="text" onkeypress="return event.charCode>=48 && event.charCode<=57" />

Solution 17 - Html

Use this.

onkeypress="return (event.charCode >= 48 && event.charCode <= 57 || event.charCode == 46)" 

You can enter whole numbers and decimal numbers.

Solution 18 - Html

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

Solution 19 - Html

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();

Solution 20 - Html

(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);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="positive_int"/>

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

Solution 21 - Html

Try this:

Yii2 : Validation rule 

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArian FaurtoshView Question on Stackoverflow
Solution 1 - HtmlQuentinView Answer on Stackoverflow
Solution 2 - HtmlKushalView Answer on Stackoverflow
Solution 3 - HtmlPavloView Answer on Stackoverflow
Solution 4 - HtmlShubham MittalView Answer on Stackoverflow
Solution 5 - HtmlHafijur Rahman SakibView Answer on Stackoverflow
Solution 6 - HtmlRogerio de MoraesView Answer on Stackoverflow
Solution 7 - HtmlDeepaliView Answer on Stackoverflow
Solution 8 - HtmlWictor ChavesView Answer on Stackoverflow
Solution 9 - HtmlArstView Answer on Stackoverflow
Solution 10 - HtmlSakawa BobView Answer on Stackoverflow
Solution 11 - HtmlAndres PaulView Answer on Stackoverflow
Solution 12 - HtmlkevinjiView Answer on Stackoverflow
Solution 13 - HtmlABDOView Answer on Stackoverflow
Solution 14 - Htmlgeeth-marathiView Answer on Stackoverflow
Solution 15 - HtmlzeroquarantaView Answer on Stackoverflow
Solution 16 - HtmlAman BansalView Answer on Stackoverflow
Solution 17 - HtmlAksabar AcceleratingView Answer on Stackoverflow
Solution 18 - HtmlFRabbiView Answer on Stackoverflow
Solution 19 - HtmlANURAG GUPTAView Answer on Stackoverflow
Solution 20 - HtmlMd. Johirul IslamView Answer on Stackoverflow
Solution 21 - Htmluser10132380View Answer on Stackoverflow