0

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 } } 
2
  • Create get fn() {} which match with regex, add this fn to formControl to ts file. i.e. this.fb.group({SiteId: ["", [ Validators.required, Validators.pattern(this.fn), ]] }); Commented Apr 4, 2022 at 10:29
  • means,i did not get you Commented Apr 4, 2022 at 10:36

1 Answer 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> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.