I see several problems in your code. You try to use the this
keyword in the validator function and this doesn’t correspond to the instance of the component. It’s because you reference the function when setting it as a validator function.
Moreover the value associated with a control can be reached in the value
property.
That said, I think that the right way to validate your two fields together is to create a group and associate a validator in it:
import { FormBuilder, Validators } from '@angular/forms';
...
constructor(private fb: FormBuilder) { // <--- inject FormBuilder
this.createForm();
}
createForm() {
this.registerForm = this.fb.group({
'name' : ['', Validators.required],
'email': ['', [Validators.required, Validators.email] ],
'passwords': this.fb.group({
password: ['', Validators.required],
repeat: ['', Validators.required]
}, {validator: this.matchValidator})
});
}
This way you will have access to all controls of the group and not only one and don’t need anymore to use the this
keyword… The group’s form controls can be accessed using the controls
property of the FormGroup. The FormGroup is provided when validation is triggered. For example:
matchValidator(group: FormGroup) {
var valid = false;
for (name in group.controls) {
var val = group.controls[name].value
(...)
}
if (valid) {
return null;
}
return {
mismatch: true
};
}
See this anwer for more details:
Edit
To display the error, you can simply use the following:
<span *ngIf="!registerForm.passwords.valid" class="help-block text-danger">
<div *ngIf="registerForm.passwords?.errors?.mismatch">
The two passwords aren't the same
</div>
</span>