模板驱动表单验证示例:
1. 必填字段:
<form #myForm="ngForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" ngModel required>
<div *ngIf="myForm.controls['username'].hasError('required')">
Username is required.
</div>
<button type="submit" [disabled]="!myForm.valid">Submit</button>
</form>
2. 最小长度验证:
<form #myForm="ngForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" ngModel required minlength="3">
<div *ngIf="myForm.controls['username'].hasError('minlength')">
Username must be at least 3 characters long.
</div>
<button type="submit" [disabled]="!myForm.valid">Submit</button>
</form>
响应式表单验证示例:
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
// ...
this.myForm = this.formBuilder.group({
username: ['', [Validators.required, Validators.minLength(3)]],
password: ['', Validators.required]
});
在模板中:
<form [formGroup]="myForm">
<label for="username">Username:</label>
<input type="text" id="username" formControlName="username">
<div *ngIf="myForm.get('username').hasError('required')">
Username is required.
</div>
<div *ngIf="myForm.get('username').hasError('minlength')">
Username must be at least 3 characters long.
</div>
<label for="password">Password:</label>
<input type="password" id="password" formControlName="password">
<div *ngIf="myForm.get('password').hasError('required')">
Password is required.
</div>
<button type="submit" [disabled]="!myForm.valid">Submit</button>
</form>
这些示例涵盖了基本的必填字段和最小长度验证,你可以根据需要添加其他验证器,比如最大长度、正则表达式验证等。Angular 表单验证的错误信息可以通过模板中的 *ngIf 来展示,也可以通过在组件中获取表单控件的错误信息来进行处理。
转载请注明出处:http://www.pingtaimeng.com/article/detail/4951/Angular