[英]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.