在StackOverflow上寻找答案时从某个地方获取了代码。我找不到感谢代码作者的链接。
我创建了一个新文件,粘贴了下面的代码,并在app.moule.ts声明中添加了指令。
import { Directive, HostListener, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[specialIsAlphaNumeric]'
})
export class SpecialCharacterDirective {
regexStr = '^[a-zA-Z0-9_]*$';
@Input() isAlphaNumeric: boolean;
constructor(private el: ElementRef) { }
@HostListener('keypress', ['$event']) onKeyPress(event) {
return new RegExp(this.regexStr).test(event.key);
}
@HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.validateFields(event);
}
validateFields(event) {
setTimeout(() => {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]/g,
'').replace(/\s/g, '');
event.preventDefault();
}, 100)
}
}
然后在mat输入中,我使用了声明
specialIsAlphaNumeric
<mat-form-field color="accent">
<input
matInput specialIsAlphaNumeric
class="form-control"
placeholder="name"
[(ngModel)]="data.projectName"
name="name"
required
minlength="4"
/>
<mat-error *ngIf="formControl.invalid">{{
getErrorMessage()
}}</mat-error>
</mat-form-field>