问题
I am wondering if there is a Validator that compares two different values from the same form - lets say I have the following:
this.loginForm = fb.group({
email: ["", Validators.required],
password: ["", Validators.required],
repeatPassword: ["", Validators.required]
});
I found this in documentation, however it wasn't very helpful.
Any ideas?
回答1:
You need to assign a validator to a complete form group to implement this. Something like that:
this.form = fb.group({
name: ['', Validators.required],
email: ['', Validators.required]
matchingPassword: fb.group({
password: ['', Validators.required],
repeatPassword: ['', Validators.required]
}
}, {validator: this.areEqual})); <--------
This way you will have access to all controls of the group and not only one... This can be accessed using the controls
property of the group control. The latter (not a single one) is directly provided when validation is triggered. For example:
areEqual(group: ControlGroup) {
var valid = false;
for (name in group.controls) {
var val = group.controls[name].value
(...)
}
if (valid) {
return null;
}
return {
areEqual: true
};
}
See this question for more details:
- Angular2 validator which relies on multiple form fields
来源:https://stackoverflow.com/questions/36064513/validators-same-as-other-value-in-form