![](/img/trans.png)
[英]Angular digits only directive still allows some characters to be written
[英]how to write a directive which takes input in text box and allows only some characters based on regex?
如果我有像[az]這樣的正則表達式,則該指令應檢查正則表達式,並且只允許使用小寫字母,並且如果嘗試在輸入中鍵入其他字符,則不應鍵入,就像未輸入一樣。 我已經閱讀過文檔,但沒有想法。
為了滿足您的要求,我分叉了現有的一個插塞。
該指令將如下所示:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[OnlyLowerCaseAlphabets]'
})
export class OnlyLowerCaseAlphabets {
constructor(private el: ElementRef) { }
@Input() OnlyLowerCaseAlphabets: boolean;
private regex: RegExp = new RegExp( /^[a-z]+$/);
@HostListener('keydown', [ '$event' ])
onKeyDown(event: KeyboardEvent) {
// 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;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
矮人在這里:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.