i am building a form in angular, and i'm using validators for each field, the html form looks like this :
<form [formGroup]="form">
<mat-form-field>
<label translate>Name field</label>
<input formControlName="name" matInput>
</mat-form-field>
...
And in the .ts file i initialize the form with:
ngOnInit() {
this.initializeForm();
}
initializeForm() {
this.form = this.fb.group({
nameControl: new FormControl(this.initialShare?.name, [Validators.required, noWhitespaceValidator]),
...
});
}
noWhitespaceValidator is a custom validator that checks if the user input consists of only whitespaces.
My question is, how could i add a piece of text that shows which validator does not pass, for example, i want to print: Name is required, if the Validators.required fails, or , Name cannot be composed of only whitespaces, if the noWhitespaceValidator fails.
CodePudding user response:
if you are using Material Inputs you can show your errors using mat-error
Like This
<mat-form-field>
<label translate>Name field</label>
<input formControlName="nameControl" matInput>
<mat-error *ngIf="form.get('nameControl').hasError('required')">Name is required</mat-error>
<mat-error *ngIf="form.get('nameControl').hasError('THE_ERROR_NAME_THAT_IS_RETURNING_FROM_VALIDATOR')"> Name cannot be composed of only whitespaces</mat-error>
</mat-form-field>
PLEASE NOTE:THE_ERROR_NAME_THAT_IS_RETURNING_FROM_VALIDATOR
field should be replaced with the key which is returning from noWhitespaceValidator
validator
CodePudding user response:
It's like @iLuvLogix said in comments
<div *ngIf="form.controls['nameControl'].errors.noWhitespaceValidator >
Name cannot be composed of only whitespaces
</div>
<div *ngIf="form.controls['nameControl'].errors.required">
Name is required
</div>
see this link: https://angular.io/guide/form-validation