简体   繁体   中英

RegEx not working in directive - Angular 4

I created a directive that validates what the user enters in text field. User can enter numbers, dots and commas but not anything else.

The validator works when entering numbers, but I cannot enter commas and dots.

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

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

private regex: RegExp = new RegExp(/^[0-9]{1,2}([,.][0-9]{1,2})?$/);

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

constructor(private el: ElementRef) {
}

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

    let current: string = this.el.nativeElement.value;
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
        event.preventDefault();
    }
}

}

I've tested the regex online and it works for numbers, dots and commas but inside the app I can't enter dots or commas. What is wrong?

You may use

private regex: RegExp = /^[0-9]{1,2}([,.][0-9]{0,2})?$/;
                                               ^

Note that {0,2} quantifier makes [0-9] match zero , one or two digits, and thus the 2. like values will no longer stop user from typing a number with a fractional part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM