Validate special characters in angular

23.8k views Asked by At
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>
2

There are 2 answers

0
n_denny On BEST ANSWER

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

0
AntonioSk On

Hopefully this helps you out:

// Array of all special characters
var specialChars = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;

// Loop through array
for (let i = 0; i < specialChars.length; i++) {
   // Checks if input contains current character
   if (this.name.includes(specialChars[i])) {
      // Your output
      console.log("User input contained a special character");
      break;
   }
}