Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngx-mask Do not allow negative value for the currency input

I need to block the type of negative value and do not allow to type more numbers than 99,999,999.99 for my input.

Here is the code which I am using for the currency input.

<input mask="separator.2" thousandSeparator="," placeholder="Currency">

Any help will be appreciated.

Also here is the Stackblitz example.

https://stackblitz.com/edit/ngx-mask-currency-input?file=src/app/app.component.html

UPDATE

I found the answer to the second part of my question. now the input looks like this

<input mask="separator.2" thousandSeparator="," separatorLimit="10000000"  placeholder="Currency">

Now just needs to be blocked the type of - character

like image 785
Ashot Aleqsanyan Avatar asked Mar 02 '23 03:03

Ashot Aleqsanyan


2 Answers

Demo you can solve with keypress event

<input (paste)="onPaste($event)" mask="separator.2" thousandSeparator=","  separatorLimit="10000000" [allowNegativeNumbers]="false" placeholder="Currency" class="form-control" (keypress)="isPositive($event)">

in component

  isPositive(event: any) { return event.key === '-' ? false : true; }

and block paste

 onPaste(event){
    event.preventDefault();
  }
like image 72
mr. pc_coder Avatar answered Apr 24 '23 12:04

mr. pc_coder


Update on 08.02.2021

Currently, allowNegativeNumbers is working. (ngx-mask version is 11.1.4)

And the input looks like this

<input 
   mask="separator.2" 
   thousandSeparator="," 
   separatorLimit="10000000"  
   [allowNegativeNumbers]="false"
   placeholder="Currency">

Update on 01.09.2020

I have created the directive for blocking the type of negative(-) values.

Here is the directive example.

import { Directive, ElementRef, OnInit, OnDestroy } from "@angular/core";
import { fromEvent } from "rxjs/internal/observable/fromEvent";
import { Subscription } from "rxjs";

@Directive({
  // tslint:disable-next-line: directive-selector
  selector: "[onlyPositive]"
})
export class OnlyPositiveDirective implements OnInit, OnDestroy {
  subscriber$: Subscription;

  constructor(private element: ElementRef<HTMLInputElement>) {}

  ngOnInit() {
    const input = this.element.nativeElement;
    this.subscriber$ = fromEvent(input, 'input').subscribe(
      (event: KeyboardEvent) => {
        if (input.value.includes('-')) {
          input.value = input.value.replace(/-/g, '');
        }
      }
    );
  }

  ngOnDestroy() {
    this.subscriber$.unsubscribe();
  }
}

Usage example

<input onlyPositive mask="separator.2" thousandSeparator="," separatorLimit="99999999" [allowNegativeNumbers]="false" placeholder="Currency">

After Adams Advice I have changed the keypress event to the input event

DEMO: https://stackblitz.com/edit/ngx-mask-currency-input?file=src/app/app.component.html

like image 26
Ashot Aleqsanyan Avatar answered Apr 24 '23 14:04

Ashot Aleqsanyan