2
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> 

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

0
public getResults(value: string): void { const counts = { numbers: 0, characters: 0, specials: 0 }; for (const char of value) { if (/\d/.test(char)) { counts.numbers++; } else if (/[a-zA-Z]/.test(char)) { counts.characters++; } else if (/[^a-zA-Z\d\s]/.test(char)) { counts.specials++; } } this.numCount = counts.numbers; this.charCount = counts.characters; this.specialCount = counts.specials; } 

1 Comment

With this approach it avoids multiple regex check for the whole input, hence optimizes the performance.
-1

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; } } 

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.