我有一个验证所有输入的表格。例如,对于“用户名”输入,我想确保它是必填字段,其次是长度不小于2或大于10(或适合我使用的其他模式)。
当任何一个验证失败时,我想显示一个错误。如果要针对每种情况显示特定的错误,该怎么办?例如:如果输入为空,则显示'required',如果值错误,则显示'invalid'。这是我的代码:
组件:
companyNamePattern = "^[a-z0-9_-]{8,15}$";
pwdPattern = "^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,12}$";
emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
this.addCompForm = fb.group({
'companyName': [null,Validators.compose([Validators.required,Validators.minLength(5),Validators.maxLength(20)])],
'companyPassword': [null,Validators.compose([Validators.required,Validators.minLength(5),Validators.maxLength(20)])],
'companyEmail': [null,Validators.compose([Validators.required,Validators.email])]
})
html:
<form [formGroup] ="addCompForm" (ngSubmit) = "addCompany(addCompForm.value)">
<p>Enter the company name:</p>
<input type="text" formControlName="companyName" >
<div class="alert" *ngIf="!addCompForm.controls['companyName'].valid && addCompForm.controls['companyName'].touched" >{{nameAlert}}</div>
<p>Enter the company password:</p>
<input type="text" formControlName="companyPassword">
<div class="alert" *ngIf="!addCompForm.controls['companyPassword'].valid && addCompForm.controls['companyPassword'].touched " >{{passAlert}}</div>
<p>Enter the company email:</p>
<input type="text" formControlName="companyEmail">
<div class="alert" *ngIf="!addCompForm.controls['companyEmail'].valid && addCompForm.controls['companyEmail'].touched " >{{emailAlert}}</div>
<br>
<br>
<div class="btn-container">
<button type="submit" [disabled]="!addCompForm.valid">
<i class="material-icons">done</i>
</button>
</div>
</form>
答案 0 :(得分:0)
*ngIf="addCompForm.get('companyName').hasError('required')
将其添加为必填字段,然后
*ngIf="addCompForm.get('companyName').hasError('minLength')
添加此内容以使minLength与最大长度相同。hasErro('maxlength')