Last active
December 27, 2019 14:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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