How to validate a field based on another field within angular reactive forms? [duplicate]

Discussão em 'Angular' iniciado por J4N, Outubro 11, 2024.

  1. J4N

    J4N Guest

    I've a form to register new users.

    I've created a formgroup with multiple fields. I've added on addition formgroup validator, that ensures that the password and confirmPassword are equals:

    authForm = this.formBuilder.group(
    {
    email: ['', [Validators.email, Validators.required]],
    password: ['', [Validators.minLength(8), Validators.required]],
    displayName: ['', [Validators.required]],
    confirmPassword: ['', [Validators.required]],
    },
    {
    validators: matchValidator(
    'password',
    'confirmPassword',
    "Passwords doesn't match"
    ),
    }
    );


    with matchValidator being:

    export function matchValidator(
    controlName: string,
    matchingControlName: string,
    errorMessage: string
    ): ValidatorFn {
    return (abstractControl: AbstractControl) => {
    const control = abstractControl.get(controlName);
    const matchingControl = abstractControl.get(matchingControlName);

    if (
    matchingControl!.errors &&
    !matchingControl!.errors?.['confirmedValidator']
    ) {
    return null;
    }

    if (control!.value !== matchingControl!.value) {
    const error = { confirmedValidator: errorMessage };
    matchingControl!.setErrors(error);
    return error;
    } else {
    matchingControl!.setErrors(null);
    return null;
    }
    };
    }


    But I'm not quite satisfied, I've some helper components that display all the errors associated with a given field. But the "Password doesn't match" doesn't get displayed because the error is not associated to the confirmPassword field.

    Is there a way to have the same kind of match validator that I've, but assigned to confirmPassword, which implies it would retrieve the password value ?

    Continue reading...

Compartilhe esta Página