How to restrict Special character in material input
Try Like this:
stackblitz example
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)
}
}
The following approach works without using the setTimeout call, which means there is no flashing of special characters in the input control when the other response by Aashish K Jha is used
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: ClipboardEvent) {
this.validateFields(event);
}
validateFields(event: ClipboardEvent) {
event.preventDefault();
const pasteData = event.clipboardData.getData('text/plain').replace(/[^a-zA-Z0-9 ]/g, '');
document.execCommand('insertHTML', false, pasteData);
}
}