事實上我覺得 響應式表單必定比模闆式表單好用一些
https://angular.cn/guide/form-validation | 官方文檔 |
---|---|
https://angular.cn/generated/live-examples/form-validation/stackblitz.html | demo |
自定義驗證器-工廠模式,是這樣的:
/** A hero's name can't match the given regular expression */
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;
};
}
模闆式:
第一步,在模闆中添加一個指令。:
providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
第二步:
響應式-自定義:
this.heroForm = new FormGroup({
'name': new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
]),
'alterEgo': new FormControl(this.hero.alterEgo),
'power': new FormControl(this.hero.power, Validators.required)
});
驗證看起來特别不舒服
https://angular.cn/guide/dynamic-form | 動态表單 |
---|---|