Reputation: 37
I'm working on a Custom Directive in Angular 13 with Reactive Forms as well as Angular Material.
I want the directive to allow only Alpha Numeric values in my Employee Number input field. What I ideally want is that the first two values should be characters and and 3 digits in total 5. It should allow to backspace.
However, in the code below, it allows to backspace as well as write as many numbers and letters as I want. It also INCLUDES SPECIAL CHARACTERS such as . , $ % ^ & * ( ) @ ! which I DONOT WANT
ALPHANUMERIC.DIRECTIVE.TS FILE
import { Directive, ElementRef, HostListener, Input, Optional } from '@angular/core';
@Directive({
selector: '[appAlphaNumeric]'
})
export class AlphaNumericDirective {
constructor() { }
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9]/.test(inp)) {
return true;
}
else {
event.preventDefault();
return false;
}
}
}
HTML FILE
<!-- Employee Number -->
<mat-form-field appearance="outline">
<mat-label>Employee Number</mat-label>
<input formControlName ="employeenumber" matInput placeholder="Placeholder"
appAlphaNumeric >
</mat-form-field>
Upvotes: 0
Views: 499