一、
1. html:
<input nz-input id="name" formControlName="name" required>
<div *ngIf="addForm.get('name').invalid && (addForm.get('name').dirty || addForm.get('name').touched)" class="alert alert-danger">
<div *ngIf="addForm.get('name').errors.required">姓名不能为空</div>
<div *ngIf="addForm.get('name').errors.minlength">姓名不得少于六位</div>
</div>
2. component:
this.addForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(6)
});
- 同步验证器函数:
required
和minlength
;(验证器函数分为同步验证器函数和异步验证器函数两种,还可以写自己的验证器) - 改变控件的值会改变控件的 dirty状态;控件失去焦点时,会改变控件的 touched状态;
- 检查dirty和touched的目的:在碰过文本框后才做出错误提示(如果不检查的话,一进入这个表单界面就会提示“姓名不能为空”);
二、 自定义验证器
- html:
<input nz-input id="name" formControlName="name" required>
<div *ngIf="addForm.get('name').invalid && (addForm.get('name').dirty || addForm.get('name').touched)" class="alert alert-danger">
<div *ngIf="addForm.get('name').errors.forbiddenName">姓名不能为 bob0</div>
</div>
- component:
this.addForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(6), forbiddenNameValidator(/bob/i)]]
});
- directive:
import { ValidatorFn, AbstractControl } from '@angular/forms';
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? {'forbiddenName': {value: control.value}} : null;
};
}