Home > Software engineering >  Custom validator - Min number of selected items in nested arrays
Custom validator - Min number of selected items in nested arrays

Time:01-24

I have the following form set-up:

this.myForm = this.fBuilder.group({
        locations: this.fBuilder.group({
          universities: this.fBuilder.array([]),
          cities: this.fBuilder.array([]),
          countries: this.fBuilder.array([])
      }, { validators: CustomValidators.minItemsInFormGroupNestedFormArrays(1)})
    });

And I've made a custom validator. I need the user to have added at least 1 item to 1 of the 3 arrays.

But I'm a bit rusty on looping through the nested objects (universities, cities and countries) to then get the total number of array items in each. So far I have:

static minItemsInFormGroupNestedFormArrays(min = 1) {
        const validator: ValidatorFn = (formGroup: AbstractControl) => {
          if (formGroup instanceof FormGroup) {
            const totalSelected = Object.entries(formGroup.controls).reduce((acc, [key, value]) => {
              acc   value.value.length;
              return acc;
            },0);
              console.log(totalSelected);
            return totalSelected >= min ? null : { required: true };
          }
      
          throw new Error('formGroup is not an instance of FormGroup');
        };
      
        return validator;
      }

But this always returns that I have 0 items even after I add items into 1 of the arrays.

I'd just need to look for the length in each array. If there is at least 1, then validation passes.

CodePudding user response:

A lot of context is missing from the question but from the validator there is one major problem in the line;

...
acc   value.value.length;
...

You need to assign a value and return the value,

...
acc = acc   value.value.length;
...
  • Related