I needed a validation that checks if email
equals Email Confirm
.
For this I created a custom validation that looks like
import { AbstractControl, ValidationErrors, FormGroup } from '@angular/forms';
export function ValidateEqual( equals: string ) {
return ( control: AbstractControl ): ValidationErrors | null => {
const equalsField = control.root.get( equals )
if ( equalsField ) {
equalsField.valueChanges.subscribe( value => {
console.log( 'observable fired', value );
// control.updateValueAndValidity( { onlySelf: true , emitEvent: false } );
} );
if ( control.value !== equalsField.value ) {
return { equals: true };
}
}
return null;
}
}
and my form looks like
this.loginForm = this.fb.group( {
password: [ '', [
Validators.required,
] ],
email: [ '', [
Validators.required,
Validators.email,
] ],
emailConfirm: [ '', [
Validators.required,
Validators.email,
ValidateEqual( 'email' ),
] ]
} );
So I am passing the field to check equality with as an argument in ValidateEqual()
. That works fine.
The following scenario fails:
1)
Email: mattijs@foo.nl
Confirm Email: mattijs@food.nl
*now Confirm email shows an error that it is not equal to `Email'. Correct.
2)
*now I change the email
field to match the confirm email
field.
Email: mattijs@food.nl
Confirm Email: mattijs@food.nl
*The error on the confirm email
field doesn't disappear because it is not aware of any change.
The issue I have is, that I am trying to use the valueChanges
observable on the equals field to have the control
field to re-validate, but when I enable control.updateValueAndValidity()
it is subscribing exponentially on each keypress and the browser will crash. IT does notify the email confirm
field to re-validate, so it almost works...almost.
Does anyone have an idea how to only have it subscribe once and make it re-validate the control
field without subscribing again (and again...)?