我有一个材料输入控件,我在用户输入时限制了特殊字符,但是当在任何编辑器中键入一些单词并复制并粘贴带有特殊字符的单词时,这是不起作用的。
我已经为此编写了指令以防止特殊字符,但是可以在复制粘贴中提供更好的解决方案限制。
应用程序组件.html:
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput specialIsAlphaNumeric placeholder="Favorite food" value="Sushi">
</mat-form-field>
<mat-form-field class="example-full-width">
<textarea matInput placeholder="Leave a comment"></textarea>
</mat-form-field>
</form>
指示:
import { Directive, HostListener, Input } from '@angular/core';
@Directive({
selector: '[specialIsAlphaNumeric]'
})
export class SpecialCharacterDirective {
regexStr = '^[a-zA-Z0-9_]*$';
@Input() isAlphaNumeric: boolean;
@HostListener('keypress', ['$event']) onKeyPress(event) {
return new RegExp(this.regexStr).test(event.key);
}
}
演示请参见此处 https://stackblitz.com/edit/angular-cijbqy-biwrck?file=app%2Finput-overview-example.ts:
https://stackblitz.com/edit/angular-cijbqy-biwrck?file=app%2Finput-overview-e[stackblit https://stackblitz.com/edit/angular-cijbqy-biwrck?file=app%2Finput-overview-e%5Bstackblit
重现步骤:
输入不允许的特殊字符:工作正常。
而复制粘贴机智允许特殊字符