'How to restrict certain strings from input in angular

I want to restrict certain string like TEST,DUMMY to be removed from text box entry, i did below code but not working

        <mat-form-field class="example-full-width" style="width:1000%">

                                                <input (input)="inputValidator($event)" matInput id="SiteId" formControlName="SiteId" placeholder="Enter Site Id" type="text" required />
                                            </mat-form-field>

In .ts file

 public inputValidator(event: any) {
    console.log('event.target'+event.target.value);
   // const pattern = /^[a-zA-Z0-9]*$/; 
   const pattern   =/^(TEST|DUMMY)$/ ; 
    //let inputChar = String.fromCharCode(event.charCode)
    if (!pattern.test(event.target.value)) {
      event.target.value = event.target.value.replace(/[^(TEST|DUMMY)$]/g, "");
      // invalid character, prevent input

    }
  }


Solution 1:[1]

You should create your own validator to test against this patterns, and then subscribe to statusChanges to check if value is valid or not, and then update the FormControl if it matches your regex.

ngOnInit(): void {
   // assuming you have a FormBuilder already in your component
   this.fb.group({ SiteId: ['', [Validators.required, customValidator]] });
   // subscribe to status changes to overwrite the value
   const siteControlSub = this.fb.get('SiteId').statusChanges.subscribe((status) => {
       const control = this.fb.get('SiteId');
       // if control is INVALID and has the custom error that we set, then replace the value
       if(status === 'INVALID' && control.hasError('invalidPattern')) {
         control.setValue(control.value.replace(/[^(TEST|DUMMY)$]/g, ""))
       }
   }
}

// custom validator function to check against a regex
customValidator(): ValidatorFn {
   return (formControl: AbstractControl): ValidationErrors | null => {
      const value = formControl.value;
      const pattern   =/^(TEST|DUMMY)$/;
      if(value.match(pattern)) {
         return { invalidPattern: true } 
      } else if(!value) {
         return { required: true } 
      }
      return true;
   }
} 

In your HTML:

<mat-form-field class="example-full-width" style="width:1000%">
    <input matInput id="SiteId" formControlName="SiteId" placeholder="Enter Site Id" type="text" />
</mat-form-field>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kanishk Anand