在Angular应用程序中,表单验证是通过使用Reactive Forms或Template-driven Forms来实现的。角度验证器(Angular Validators)用于在用户输入时检查表单控件的值是否有效。当验证失败时,错误信息需要以某种方式显示给用户。
<form [formGroup]="registerForm">
<div>
<label for="email">Email</label>
<input id="email" formControlName="email">
<div *ngIf="registerForm.get('email').invalid && (registerForm.get('email').dirty || registerForm.get('email').touched)">
<div *ngIf="registerForm.get('email').errors.required">Email is required.</div>
<div *ngIf="registerForm.get('email').errors.email">Invalid email format.</div>
</div>
</div>
<!-- 其他表单字段 -->
</form>
<form #registerForm="ngForm">
<div>
<label for="email">Email</label>
<input id="email" name="email" [(ngModel)]="user.email" required email>
<div *ngIf="registerForm.controls['email'].invalid && (registerForm.controls['email'].dirty || registerForm.controls['email'].touched)">
<div *ngIf="registerForm.controls['email'].errors?.required">Email is required.</div>
<div *ngforEach="let error of registerForm.controls['email'].errors | keyvalue">{{error.key}}: {{error.value}}</div>
</div>
</div>
<!-- 其他表单字段 -->
</form>
dirty
或touched
,或者验证器没有正确设置。通过以上方法,您可以在Angular应用程序中有效地显示来自角度验证器的错误信息。
领取专属 10元无门槛券
手把手带您无忧上云