angulartypescriptangular-reactive-formsangular-validation

Angular Custom Validation Control doesn't get form value


This code in my form-validators.ts:

console.log('password:', password?.value);
console.log('confirmPwd:', confirmPwd?.value);

always fetched me undefined, causing the custom validation (matchPwdValidator()) to constantly return false. If I fetched confirmPwd in the switch, it will print out the correct details. Below is a summarized version of my codes.

form-validators.ts

import { AbstractControl, ValidatorFn, Validators } from "@angular/forms";

export class FormValidators {
  ...

  static matchPwdValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      const password = control.get("password");
      const confirmPwd = control.get("confirmPwd");
  
      console.log('password:', password?.value);
      console.log('confirmPwd:', confirmPwd?.value);
  
      if (!password || !confirmPwd || password.value !== confirmPwd.value) {
        return { PwdNotMatched: true };
      }
  
      return null;
    };
  }
}

form.component.ts

import { Component } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
import { FormValidators } from "../utilities/form-validators";

@Component({
  selector: "app-form",
  templateUrl: "./form.component.html",
  styleUrls: ["./form.component.scss"],
})
export class FormComponent {
  
  cpwdError: boolean = false;

  sampleForm: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
  ) {
    
    this.sampleForm= this.formBuilder.group(
      {
        ...
        password: ["", FormValidators.passwordValidator()],
        confirmPwd: ["", FormValidators.matchPwdValidator()],
      },
    );
    
    ...
    this.sampleForm.get('confirmPwd')?.statusChanges .subscribe(() => {
      this.updateErrorFlags('confirmPwd');
    });
  }


  private updateErrorFlags(controlName: string): void {
    const control = this.sampleForm.get(controlName);
    if (control) {
      switch (controlName) {
        ...
        case 'confirmPwd':
          this.cpwdError = control.hasError('PwdNotMatched') && control.dirty;
          break;
      }
    }
  }
}

Solution

  • You are set the matchPwdValidator validation to the "confirmPwd" FormControl. It can't find any control with name: "password" and "confirmPwd". You should get both controls from the root form group of the current form control.

    const password = control.parent?.get('password');
    const confirmPwd = control.parent?.get('confirmPwd');
    

    Demo @ StackBlitz