Search code examples
angularngx-mask

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


Solution

  • 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