簡體   English   中英

RegEx 在指令中不起作用 - Angular 4

[英]RegEx not working in directive - Angular 4

我創建了一個指令來驗證用戶在文本字段中輸入的內容。 用戶可以輸入數字、點和逗號,但不能輸入任何其他內容。

輸入數字時驗證器工作,但我不能輸入逗號和點。

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();
    }
}

}

我已經在線測試了正則表達式,它適用於數字、點和逗號,但在應用程序中我無法輸入點或逗號。 怎么了?

您可以使用

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

請注意, {0,2}量詞使[0-9]匹配、一位或兩位數字,因此2. like 值將不再阻止用戶輸入帶有小數部分的數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM