I am trying to compare the value of password and confirm password and if found mismatch then message to be shown.
Due to some reasons it shows nothing. Am I missing anything in below code?
Form Group Validation work
this.resetPasswordForm = new FormGroup({
password: new FormControl("", [
Validators.required,
Validators.minLength(8),
Validators.maxLength(40)
]),
password_confirmation: new FormControl("", [
Validators.required
]),
});
Html
<input type="password" formControlName="password_confirmation" />
<span *ngIf="resetPasswordForm.controls.password_confirmation.errors
&& resetPasswordForm.controls.password_confirmation.dirty
&& resetPasswordForm.controls.password_confirmation.touched">
<ng-container *ngIf="resetPasswordForm.controls.password_confirmation.errors.required;else second">
Confirm password is required
</ng-container>
<ng-template #second>
<ng-container *ngIf="resetPasswordForm.controls.password_confirmation.value
== resetPasswordForm.controls.password.value">
Password and confirm password mismatch
</ng-container>
</ng-template>
</span>
Your password_confirmation validation only has Validation.required. So when this field has any value, resetPasswordForm.controls.password_confirmation.errors will be false and any error message will not be shown.
You have to create a validation function that checks the password and password_confirmation values are identical. This will resetPasswordForm.controls.password_confirmation.errors makes true when two fields have different values.
const validatePasswordMatch = (control: AbstractControl): {[key: string]: any} | null => {
const password = this.resetPasswordForm?.get('password')?.value as string;
const passwordConfirm = control.value as string;
if (password !== passwordConfirm) {
return {passwordMatch: true};
}
return null;
};
this.resetPasswordForm = new FormGroup({
password: new FormControl("", [
Validators.required,
Validators.minLength(8),
Validators.maxLength(40)
]),
password_confirmation: new FormControl("", [
Validators.required,
validatePasswordMatch
]),
});
Then you can show password confirmation error like this.
<ng-template #second>
<ng-container *ngIf="resetPasswordForm.controls.password_confirmation.errors.passwordMatch">
Password and confirm password mismatch
</ng-container>
</ng-template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With