Home > Software engineering >  Custom validator for dynamically generated checkbox in reactive form is not working
Custom validator for dynamically generated checkbox in reactive form is not working

Time:04-30

I have created a project in Angular 13 version for validating the dynamically generated checkboxes. I have followed this blog (enter image description here

CodePudding user response:

ValidatorFn has the following type:

export declare interface ValidatorFn {
    (control: AbstractControl): ValidationErrors | null;
}

So you need to change the function like this:

function minSelectedCheckboxes(min = 1) {
  const myValidator: ValidatorFn = (control: AbstractControl) => {
    const formArray = control as FormArray;
    const totalSelected = formArray.controls
      .map((control) => control.value)
      .reduce((prev, next) => (next ? prev   next : prev), 0);
    return totalSelected >= min ? null : { required: true };
  };

  return myValidator;
}
  • Related