Search code examples
angularcustomvalidator

Custom validator for dynamically generated checkbox in reactive form is not working


I have created a project in Angular 13 version for validating the dynamically generated checkboxes. I have followed this blog (https://coryrylan.com/blog/creating-a-dynamic-checkbox-list-in-angular). In this blog, there is a custom validation. But the validation is not working for me. The custom validator code is:

function minSelectedCheckboxes(min = 1) {
    const myValidator: ValidatorFn = (formArray: 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;
}

But I am getting the below error. Can anyone help me to solve the error?

src/app/app.component.ts:62:8 - error TS2322: Type '(formArray: FormArray) => { required: boolean; } | null' is not assignable to type 'ValidatorFn'. Types of parameters 'formArray' and 'control' are incompatible. Type 'AbstractControl' is missing the following properties from type 'FormArray': controls, at, push, insert, and 6 more.

62 const myValidator: ValidatorFn = (formArray: FormArray) => { ~~~~~~~~~~~

enter image description here


Solution

  • 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;
    }