Mic*_*ryl 3 typescript angular2-forms angular
我正在尝试使用Reactive Forms模块在Angular 2中构建注册表单.因此,我有一个为表单定义的FormGroup,然后我可以在其中列出每个FormControl的验证器.
考虑这个部分类:
export class TestFormComponent implements OnInit {
form: FormGroup;
password = new FormControl("", [Validators.required]);
passwordConfirm = new FormControl("", [Validators.required, this.validatePasswordConfirmation]);
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.form = this.fb.group({
"password": this.password,
"passwordConfirm": this.passwordConfirm
});
}
validatePasswordConfirmation(fc: FormControl) {
var pw2 = fc.value;
var pw = // how do I get this value properly????
if (pw === '') {
return {err:"Password is blank"};
}
if (pw2 === '') {
return {err:"Confirmation password is blank"};
}
if (pw !== pw2) {
return {err:"Passwords do not match"}
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以看到我为该passwordConfirm字段创建了验证器,但我不知道如何获取主password字段的值(用于pw验证器中)以进行比较.
我不能只引用this.form.value.password因为this在验证器中没有引用包含表单的主类.
有任何想法吗?
Mic*_*ryl 19
所以答案结果是在表单上放置一个新的验证器,然后使用传递给验证器的FormGroup对象作为比较字段值的方法.我怀疑的那么多.然而,我缺少的是如何在单个passwordConfirm字段上正确设置错误状态.此代码显示了如何执行此操作:
export class TestFormComponent implements OnInit {
form: FormGroup;
password = new FormControl("", [Validators.required]);
passwordConfirm = new FormControl("", [Validators.required, this.validatePasswordConfirmation]);
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.form = this.fb.group({
"password": this.password,
"passwordConfirm": this.passwordConfirm
},
{
validator: this.validatePasswordConfirmation
});
}
validatePasswordConfirmation(group: FormGroup) {
var pw = group.controls['password'];
var pw2 = group.controls['passwordConfirm'];
if (pw.value !== pw2.value) { // this is the trick
pw2.setErrors({validatePasswordConfirmation: true});
}
// even though there was an error, we still return null
// since the new error state was set on the individual field
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
如上面代码中的注释所述,技巧是您可以FormControl使用该setErrors()方法在各个字段上设置错误状态.现在,使用此代码,确认字段将根据其具有的常规验证器Validators.required以及我们添加的基于自定义表单的验证器获取正确的有效/无效状态集.
使用此方法,您可以创建复杂的基于表单的验证器,可以检查许多不同表单字段的状态,并根据您可以提出的任何业务逻辑单独设置验证状态.这使得使用Angular 2 Reactive表单的跨字段验证非常简单.
| 归档时间: |
|
| 查看次数: |
7275 次 |
| 最近记录: |