Skip to content

Instantly share code, notes, and snippets.

@Streeterxs
Last active December 27, 2019 14:28
Show Gist options
  • Save Streeterxs/3c53a654d1b2b95b845a235fc430f50a to your computer and use it in GitHub Desktop.
Save Streeterxs/3c53a654d1b2b95b845a235fc430f50a to your computer and use it in GitHub Desktop.
This function make a validation and setErrors to the form, without the need of creating a StateMatcher to setErrors
import { AbstractControl } from "@angular/forms";
export function passwordMatchValidator(control: AbstractControl): {[key: string]: boolean} | null {
const password = control.get('password');
const passwordRepeat = control.get('passwordRepeat');
const passwordErrors = { ...password.errors };
const passwordRepeatErrors = { ...passwordRepeat.errors };
if (password.value !== passwordRepeat.value) {
password.setErrors({passwordMatchValidator: true});
passwordRepeat.setErrors({passwordMatchValidator: true});
return {passwordMatchValidator: true};
} else {
delete passwordErrors.passwordMatchValidator;
delete passwordRepeatErrors.passwordMatchValidator;
if(Object.keys(passwordRepeatErrors).length > 0) {
passwordRepeat.setErrors({...passwordRepeatErrors});
} else {
passwordRepeat.setErrors(null);
}
if(Object.keys(passwordErrors).length > 0) {
password.setErrors({...passwordErrors});
} else {
password.setErrors(null);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment