0

The custom percentage validator below takes a beneficiaries array as a parameter. beneficiary form is built with planPercents with percent as a formConrol. The console log works for any any plan having over 100% distribution. However, I am unable to successfully return invalid and mark the formArray as invalid.

beneficiaries: this.fb.array([], PercentValidator.beneficiaryDistValidator),  

    getPlanPercentGroup(): FormGroup {
        return this.fb.group({
          planUnitId: [null, Validators.required],
          percent: [0, Validators.required],
        });
      }


        import {FormArray} from '@angular/forms';

            export class PercentValidator {

              static beneficiaryDistValidator(formArray: FormArray): ValidationResult {
                if (formArray.controls.length) {
                  // if there is at least one beneficiary
                  const planPercentArray = formArray.at(0).get('planPercents') as FormArray;
                  if (planPercentArray && planPercentArray.controls.length) {
                    for (let i = 0; i < planPercentArray.controls.length; i++) {
                      let planPercentCounter = 0;
                      formArray.controls.forEach(beneficiary => {
                        const planPercentArray2 = beneficiary.get('planPercents') as FormArray;
                        planPercentCounter += planPercentArray2.at(i).get('percent').value;
                        if (planPercentCounter > 100) {
                          console.log('Invalid');
                          return {Invalid: true};
                        }
                      });
                    }
                  }
                }
                return null;
              }
            }

            export interface ValidationResult {
              [key: string]: boolean;
            }
1
  • 1
    That's because you're trying to return from inside a forEach callback Commented Jan 16, 2020 at 22:13

1 Answer 1

1

That's because you're trying to return from inside a forEach callback. You have to define a variable outside the callback, and assign it from inside. Then you'll be able to return it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.