0

  • 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>   
  • Your directive is not being triggered at all.. you need to add `@HostListener('keydown', ['$event'])` before your `keyPressAlphanumeric` function, and then test your RegEx. – Mohamed Karkotly Jul 02 '22 at 20:23
  • Thank you for the response. I added the @HostListener just like you told, but its still allowing me to write special characters and add space in between characters and numbers in my input field. – Maryam Faheem Jul 02 '22 at 20:37
  • Use this RegEx `^[A-Za-z]{2}[0-9]{3}$`. – Mohamed Karkotly Jul 02 '22 at 21:42
  • Its still the same case, after using your regex, seems like the directive isn't working at all. Still allows me to write special characters as well as write numbers in the beginning. Also lets me add space between values. Cant figure out the issue, as I've tried several other RegExp's but the same thing occurs with each one. – Maryam Faheem Jul 03 '22 at 04:41
  • It's not that the RegEx is not working, it works, here's a demonstration link https://regex101.com/r/3CdX82/1 The problem is that you don't seem like you correctly regestered your directive. Try adding a `console.log()` and see if your `keyPressAlphanumeric` function is being called or not. – Mohamed Karkotly Jul 03 '22 at 18:12
  • I saw the link, it works perfectly there. I added console.log my function is not being called. – Maryam Faheem Jul 03 '22 at 19:00
  • Since no enough code is provided regarding regestration of your directive, I'll provide a workaround. in your `.ts` file, and inside `this.formBuilder.group` function, you can add the following to your `employeenumber` field: `employeenumber: [null, [Validators.required, Validators.pattern('^[A-Za-z]{2}[0-9]{3}$')]]` – Mohamed Karkotly Jul 03 '22 at 19:14

0 Answers0