Home > OS >  How to add RegExp to an angular 8 directive to support negative decimal number?
How to add RegExp to an angular 8 directive to support negative decimal number?

Time:01-23

I have the following directive:

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

@Directive({
    selector: '[signedNumeric]'
})

export class SignedNumericDirective {
   
    private regex = {               
        decimal: new RegExp(/^[0-9] (?:\.[0-9]{0,2})?$/g)
    };                          
    private specialKeys = {       
        decimal: [ 'Backspace', 'Delete', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight' ]
    };

    constructor(private el: ElementRef) {
    }

    @HostListener('keydown', [ '$event' ])
    onKeyDown(event: KeyboardEvent) {

        if (this.specialKeys['decimal'].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;
        let next: string = current.concat(event.key);
        if (next && !String(next).match(this.regex['decimal'])) {
            event.preventDefault();
        }
    }
}

This is how how use the directive in the template:

<input type="text" name="sample" id="sample" autocomplete="off"
                                  [(ngModel)]="decinmalVal" maxlength="6" signedNumeric>

This worked for positive decimal such as 34.45 0.7 1200.6 BUT it's not allow negative. I've try to update the RegExp to:

decimal: new RegExp(/^-?[0-9]\d*(\.\d )?$/g)

with no success. The reg exp was tested online but it doesn't work in the directive. I don't know what wrong.

CodePudding user response:

You can use the following regex for live input validation

/^-?\d*(?:\.\d*)?$/

Details:

  • ^ - start of string
  • -? - an optional -
  • \d* - zero or more digits
  • (?:\.\d*)? - an optional sequence of a dot and then zero or more digits
  • $ - end of string.
  • Related