参考:
1、angular2的formGroup验证问题
https://segmentfault.com/q/1010000019395911
2、Angular如何在创建控件后将验证器添加到FormControl?(Angular How to add Validator to FormControl after control is created?)
http://www.it1352.com/773589.html
// 构建表单
private createForm() {
this.form = this.formBuilder.group({
Name: ["", Validators.required],
Mobile: ["", Validators.required],
AuthCode: [""],
Sex: ["", Validators.required],
Birthday: ["", Validators.required],
Agree: [true, Validators.required],
});
// 绑定dataChange
this.form.controls["Agree"].valueChanges.subscribe((value) => {
this.agree = value;
});
this.form.controls["Mobile"].valueChanges.subscribe((value) => {
let isValidMobile = value && value.length == 11 && this.utils.isTel(value);
this.isVisibleAuthCode = (isValidMobile && value !== this._oldMobile); // 有效且不等于旧号码 可见
this.isDisabledAuthCode = !isValidMobile;
if (this.isVisibleAuthCode) {
// 加上“必填”
this.form.controls["AuthCode"].setValidators([Validators.required]);
}
else {
// 去除“必填” (2行)
this.form.controls["AuthCode"].setErrors(null);
this.form.controls["AuthCode"].clearValidators();
}
});
}