我使用的是Angular 6,我有一个表单,里面有两个字段Name和Display name。我对这两个字段都有3-4个验证,例如必填,图案,最小长度,最大长度。我想一次只显示一条错误消息。如何实现?
这是示例代码。
<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>
答案 0 :(得分:1)
您可以尝试ngTemplate * ngIf,否则
<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>
答案 1 :(得分:0)
尝试这样:
模板:
<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"
}
}
答案 2 :(得分:0)
代替使用
检查错误nameInput.errors.minlength
您应该像这样使用hasError
-
nameInput.hasError('min')