[英]Angular Directive Regex Alphanumeric Validation
I'm kinda new to Angular and Regex and I'm currently stuck with a problem.我对 Angular 和 Regex 有点陌生,我目前遇到了一个问题。 I need to create an Angular Directive that allows an input field to do the following:我需要创建一个允许输入字段执行以下操作的 Angular 指令:
I've done numbers 1-3 my problem comes in #4.我已经完成了数字 1-3,我的问题出现在 #4。 The input still accepts '_', '`', '&', 'ˆ' and some other special characters.输入仍然接受 '_'、'`'、'&'、'^' 和其他一些特殊字符。 I just need to negate all special characters.我只需要否定所有特殊字符。
Here is my directive:这是我的指令:
export class AlphaNumericFieldDirective{
private regex: RegExp = new RegExp(/^[a-zA-Z]([a-zA-Z0-9]+ ?)*$/);
private specialKeys: Array<string> = ['Backspace', 'Space', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) {}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
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();
}
}
}
And here is the sample output featuring some of the characters I want to negate这是示例 output 包含一些我想否定的字符
I would appreciate the help, thanks我将不胜感激,谢谢
This solution is working for me.这个解决方案对我有用。
import { Directive, HostListener } from "@angular/core";
@Directive({
selector: "[appAlphabetOnly]",
})
export class AlphabetOnlyDirective {
@HostListener("keydown", ["$event"]) public onKeydown(event: KeyboardEvent) {
if (
(event.keyCode >= 15 && event.keyCode <= 64) ||
event.keyCode >= 123 ||
(event.keyCode >= 96 && event.keyCode <= 105)
) {
event.preventDefault();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.