Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want the total to be exactky 100. but this Validator doesn't work. What is wrong in my code?

export class CustomValidators { 
  public static verticalTotal(total: number, refControl: string) {
    return (control: FormArray): ValidationErrors | null => {
      const arrayValue = control.value || [];
      let actualTotal = 0;
      control.controls.forEach(ctrl => {
        actualTotal += +(ctrl.get(refControl).value);
     });
  return actualTotal !== total ?
     { verticalTotal: true,
       message: `Total should be ${total}, not ${actualTotal}`
     } : null;
    };
   } 
}

I apply the validator like this

 this.itemForm = this.fb.group({
  subsidiaries: this.fb.array([], {
    validators: [CustomValidators.verticalTotal(100, 'percent')]
  })
}, { validators: [] });

const line = this.fb.group({
  'name': ['', []],
  'percent': [0, []]
});
(this.itemForm.get('subsidiaries') as FormArray).push(line);

this.itemForm.get('subsidiaries').updateValueAndValidity();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
190 views
Welcome To Ask or Share your Answers For Others

1 Answer

Thank you @Eliseo You are right. My code works. Except the object I return did not contain a definition for message. it had to be

   {
    verticalTotal: { valid: false,
                     message: `Total should be ${total}, not ${actualTotal}`}
    } : null;

instead of what was in my code. This way I could set the error message inside the component template.

EDITS: another thing I dit was to use the value, not the actualTotal += +(ctrl.get(refControl).value);. Here's the edited part

 arrayValue.forEach(ctrl => {
    actualTotal += +(ctrl[refControl]);
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...