[html] Is there any way to prevent input type="number" getting negative values?

I want to get only positive values, is there any way to prevent it using only html
Please don't suggest validation method

Screenshot of input control

This question is related to html input numbers

The answer is


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!


_x000D_
_x000D_
If Number is Negative or Positive Using ES6’s Math.Sign_x000D_
_x000D_
const num = -8;_x000D_
// Old Way_x000D_
num === 0 ? num : (num > 0 ? 1 : -1); // -1_x000D_
_x000D_
// ES6 Way_x000D_
Math.sign(num); // -1
_x000D_
_x000D_
_x000D_


Restrict the charcter (-) & (e) in type Number

<input type="number" onkeydown="return event.keyCode !== 69 && event.keyCode !== 189" />

Demo: https://stackblitz.com/edit/typescript-cwc9ge?file=index.ts


Easy method:

_x000D_
_x000D_
<input min='0' type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
_x000D_
_x000D_
_x000D_


The answer to this is not helpful. as its only works when you use up/down keys, but if you type -11 it will not work. So here is a small fix that I use

this one for integers

  $(".integer").live("keypress keyup", function (event) {
    //    console.log('int = '+$(this).val());
    $(this).val($(this).val().replace(/[^\d].+/, ""));
    if (event.which != 8 && (event.which < 48 || event.which > 57))
    {
        event.preventDefault();
    }
   });

this one when you have numbers of price

        $(".numeric, .price").live("keypress keyup", function (event) {
     //    console.log('numeric = '+$(this).val());
    $(this).val($(this).val().replace(/[^0-9\,\.]/g, ''));

    if (event.which != 8 && (event.which != 44 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
   });

This solution allows all keyboard functionality including copy paste with keyboard. It prevents pasting of negative numbers with the mouse. It works with all browsers and the demo on codepen uses bootstrap and jQuery. This should work with non english language settings and keyboards. If the browser doesn't support the paste event capture (IE), it will remove the negative sign after focus out. This solution behaves as the native browser should with min=0 type=number.

Markup:

<form>
  <input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
  <input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>

Javascript

$(document).ready(function() {
  $("input.positive-numeric-only").on("keydown", function(e) {
    var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
    if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
      e.preventDefault();
    }
  });

  $("input.positive-numeric-only").bind("paste", function(e) {
    var numbers = e.originalEvent.clipboardData
      .getData("text")
      .replace(/[^0-9^.^,]/g, "");
    e.preventDefault();
    var the_val = parseFloat(numbers);
    if (the_val > 0) {
      $(this).val(the_val.toFixed(2));
    }
  });

  $("input.positive-numeric-only").focusout(function(e) {
    if (!isNaN(this.value) && this.value.length != 0) {
      this.value = Math.abs(parseFloat(this.value)).toFixed(2);
    } else {
      this.value = 0;
    }
  });
});

This code is working fine for me. Can you please check:

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

Just adding another way of doing this (using Angular) if you don't wanna dirt the HTML with even more code:

You only have to subscribe to the field valueChanges and set the Value as an absolute value (taking care of not emitting a new event because that will cause another valueChange hence a recursive call and trigger a Maximum call size exceeded error)

HTML CODE

<form [formGroup]="myForm">
    <input type="number" formControlName="myInput"/>
</form>

TypeScript CODE (Inside your Component)

formGroup: FormGroup;

ngOnInit() { 
    this.myInput.valueChanges 
    .subscribe(() => {
        this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
    });
}

get myInput(): AbstractControl {
    return this.myForm.controls['myInput'];
}

I wanted to allow decimal numbers and not clear the entire input if a negative was inputted. This works well in chrome at least:

<input type="number" min="0" onkeypress="return event.charCode != 45">

_x000D_
_x000D_
<input type="number" name="credit_days" pattern="[^\-]+" _x000D_
    #credit_days="ngModel" class="form-control" _x000D_
    placeholder="{{ 'Enter credit days' | translate }}" min="0" _x000D_
    [(ngModel)]="provider.credit_days"_x000D_
    onkeypress="return (event.charCode == 8 || event.charCode == 0 || _x000D_
    event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= _x000D_
    57" onpaste="return false">
_x000D_
_x000D_
_x000D_


For me the solution was:

_x000D_
_x000D_
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
_x000D_
_x000D_
_x000D_

Edit

As suggested on the comments with a minor change to work if 0 is the min value.

_x000D_
_x000D_
<input type="number" min="0" oninput="this.value = 
 !!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
_x000D_
_x000D_
_x000D_


Here is a solution that worked best of me for a QTY field that only allows numbers.

// Only allow numbers, backspace and left/right direction on QTY input
    if(!((e.keyCode > 95 && e.keyCode < 106) // numpad numbers
        || (e.keyCode > 47 && e.keyCode < 58) // numbers
        || [8, 9, 35, 36, 37, 39].indexOf(e.keyCode) >= 0 // backspace, tab, home, end, left arrow, right arrow
        || (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + A
        || (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + C
        || (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + X
        || (e.keyCode == 86 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + V
    )) {
        return false;
    }

The @Manwal answer is good, but i like code with less lines of code for better readability. Also i like to use onclick/onkeypress usage in html instead.

My suggested solution does the same: Add

min="0" onkeypress="return isNumberKey(event)"

to the html input and

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}

as a javascript function.

As said, it does the same. It's just personal preference on how to solve the problem.


I was not satisfied with @Abhrabm answer because:

It was only preventing negative numbers from being entered from up/down arrows, whereas user can type negative number from keyboard.

Solution is to prevent with key code:

_x000D_
_x000D_
// Select your input element._x000D_
var number = document.getElementById('number');_x000D_
_x000D_
// Listen for input event on numInput._x000D_
number.onkeydown = function(e) {_x000D_
    if(!((e.keyCode > 95 && e.keyCode < 106)_x000D_
      || (e.keyCode > 47 && e.keyCode < 58) _x000D_
      || e.keyCode == 8)) {_x000D_
        return false;_x000D_
    }_x000D_
}
_x000D_
<form action="" method="post">_x000D_
  <input type="number" id="number" min="0" />_x000D_
  <input type="submit" value="Click me!"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Clarification provided by @Hugh Guiney:

What key codes are being checked:

  • 95, < 106 corresponds to Numpad 0 through 9;
  • 47, < 58 corresponds to 0 through 9 on the Number Row; and 8 is Backspace.

So this script is preventing invalid key from being entered in input.


Here's an angular 2 solution:

create a class OnlyNumber

import {Directive, ElementRef, HostListener} from '@angular/core';

@Directive({
  selector: '[OnlyNumber]'
})
export class OnlyNumber {

  // Allow decimal numbers. The \. is only allowed once to occur
  private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);

  // Allow key codes for special events. Reflect :
  // Backspace, tab, end, home
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];

  constructor(private el: ElementRef) {
  }

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }

    // Do not use event.keycode this is deprecated.
    // See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
    let current: string = this.el.nativeElement.value;
    // We need this because the current value on the DOM element
    // is not yet updated with the value from this event
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

add OnlyNumber to declarations in app.module.ts and use like it like this anywhere in your app

<input OnlyNumber="true">

oninput="this.value=(this.value   < Number(this.min) || this.value   > Number(this.max))  ? '' : this.value;"

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python