angularformsangular6angular8

Validate special characters in angular


ngOnInit(): void {
  this.customerForm = this.fb.group({
    name: ['', Validators.required],
    customer_id: ['', Validators.required],        
  })
}

I have this form group in angular. So This a form which contains name and customer_id. What I need is that I want to validate the name field.It shouldn't accept any special characters. If possible please mention also to mention in using toastr

<td>
    <mat-form-field>
        <mat-label>Name</mat-label>
        <input matInput placeholder="Name" formControlName="name" autocomplete="off" required>
    </mat-form-field>
</td>

Solution

  • You can create a custom validator to add to your form "name" so everytime the check fails the form will return an invalid state so you can show a message somewhere

    export class CustomValidators {
        nameValidator(control: FormControl): { [key: string]: boolean } {
            const nameRegexp: RegExp = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
            if (control.value && nameRegexp.test(control.value)) {
               return { invalidName: true };
            }
        }
    }
    

    Now add the CustomValidators to the component constructor:

    ...
    export class YourComponent implements OnInit {
        constructor(private customValidators: CustomValidators) {
            this.customerForm = this.fb.group({
                name: ['', Validators.compose([Validators.required, this.customValidators.nameValidator])],
                customer_id: ['', Validators.required],
            });
        }
    }
    

    It's then possible to show a mat-error to the user on the template just under the mat-form-field

    <td>
        <mat-form-field>
            <mat-label>Name</mat-label>
            <input matInput placeholder="Name" formControlName="name" autocomplete="off" required>
        </mat-form-field>
        <mat-error *ngIf="form.controls['name'].hasError('invalidName')">
            Special characters not allowed!
        </mat-error>
    </td>
    

    You can do something similar with the Validators.required built-in.

    For more informations about form validation check this