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:
<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>
directive:
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-e[stackblit
Steps to reproduce:
type it special character which is not allowed : working fine. while copy paste wit allows special character
onchange
oronChange
instead ofkeypress
– Centarehttps://stackblitz.com/edit/angular-cijbqy-biwrck?file=app/specialChracter.directive.ts
– Stoker