Reputation: 1733
I am using Angular 6 and I have a form and inside that I have two fields Name and Display name. I have 3-4 validation on both the fields like required, pattern, min length, max length. I want to display only single error message at a time. How to achieve that?
Here is the sample code.
<mat-form-field required>
<label for="attribute_name">Name</label>
<input type="text"
required
matInput
[(ngModel)]="attribute.name"
name="name"
id="attribute_name"
#nameInput="ngModel"
[ngClass]="{'form-validation--error-border' : (nameInput?.errors && (nameInput?.dirty || nameInput?.touched)) || false}"
[minlength]="3"
[maxlength]="63"
[pattern]="[some pattern]" />
<ul *ngIf="nameInput.errors && (nameInput.dirty || nameInput.touched)" class="form-validation form-validation--error">
<li *ngIf="nameInput.errors.required">Name is required</li>
<li *ngIf="nameInput.errors.minlength">Minimum length should be 3.</li>
<li *ngIf="nameInput.errors.pattern">It should start with letter.</li>
</ul>
</mat-form-field>
Upvotes: 2
Views: 1762
Reputation: 22203
Try like this:
Template:
<ul *ngIf="nameInput.errors && (nameInput.dirty || nameInput.touched)" class="form-validation form-validation--error">
<li [innerHtml]="getErrorMessage(nameInput.errors)"></li>
</ul>
TS:
getErrorMessage(errors: any) {
if (errors.required) {
return "Name is required"
} else if (errors.minlength) {
return "Minimum length should be 3"
} else if (errors.pattern) {
return "It should start with letter"
}
}
Upvotes: 0
Reputation: 86790
Instead of checking error using
nameInput.errors.minlength
You should use hasError
like this -
nameInput.hasError('min')
Upvotes: 0
Reputation: 9774
You can try ngTemplate *ngIf, else
<ul *ngIf="nameInput.errors && (nameInput.dirty || nameInput.touched)" class="form-validation form-validation--error">
<li *ngIf="nameInput.errors.required; else minLengthElem;">Name is required</li>
</ul>
<ngTemplate #minLengthElem>
<li *ngIf="nameInput.errors.minlength; else patternElem;">Minimum length should be 3.</li>
</ngTemplate>
<ngTemplate #patternElem>
<li *ngIf="nameInput.errors.pattern">It should start with letter.</li>
</ngTemplate>
Upvotes: 5