Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular way to stop negative values from being entered in input type number (on copy-paste & increase, decrease) also

my requirement is in an angular project i'm taking number input in a form like this

<input type="number" #input class="form-control" [(ngModel)]="dataItem.quantity"

i should not allow user to enter negative values even from copy-paste or through increase / decrease button of input type number or thought keyboard.

how can we acheive this, i have seen some directives, there they are taking input as 'text', my case is it should be "input type number" only.

It should allow decimals also.

Please Help me.

like image 451
Shaik Habeeb Avatar asked Apr 25 '26 10:04

Shaik Habeeb


2 Answers

You can do like below

HTML:

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

TS:

checkValue(event) {
  if (event.target.value < 0) {
    event.target.value = 0;
  }
}

You can use (keyup) too

Update:

In the Angular way, you can create a pipe. Working stackblitz

In the HTML:

<input type="number" min="0" [ngModel]="testValue | nonegativevalue" (ngModelChange)="testValue=$event">

nonegativevaluepipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'nonegativevalue'})
export class NoNegativeValue implements PipeTransform {
  transform(value: number): number {
    if(value < 0) {
      value = 0;
      return value;
    }
    return value;
  }
}

If you use reactive form, then check this stackblitz

like image 111
Sivakumar Tadisetti Avatar answered Apr 27 '26 01:04

Sivakumar Tadisetti


Try this..

<input type="number" min="0" #input class="form-control" [(ngModel)]="dataItem.quantity" 
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
like image 38
aks44 Avatar answered Apr 27 '26 02:04

aks44



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!