如何限制材料输入中的特殊字符 [英] How to restrict Special character in material input
本文介绍了如何限制材料输入中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个素材输入控件,我在用户输入时限制了特殊字符,但是当在任何编辑器中键入某些单词并复制并粘贴具有特殊字符的单词时,这是行不通的.
I have a material input control, i have restrict the special character while user enter, but when type some words in any editor and copy and paste the words with special character, which is not working.
我已经为此写了指令以防止特殊字符,但是可以提供更好的解决方案限制复制粘贴.
I have write the directive for that to prevent special character,but can one provide the better solution restrict in copy paste.
app.component.html:
app.component.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);
}
}
复制步骤:
输入不允许的特殊字符:可以正常工作. 而复制粘贴机智则允许使用特殊字符
type it special character which is not allowed : working fine. while copy paste wit allows special character
推荐答案
像这样尝试:
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)
}
}
这篇关于如何限制材料输入中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文