Issue
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.
Solution
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
Answered By - Ashot Aleqsanyan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.