Tuesday, 1 September 2020

Angular FormGroup add a custom validator

 https://stackoverflow.com/questions/56995560/adding-custom-validator-to-whole-form-group-in-angular-reactive-from



his.myFormGroup = this.formBuilder.group({ 
                     ... my group info ... 
                   }, {validators: [... validators ... ]);

the custom validator acts like any other, but the abstract control in this case is a FormGroup that can be treated like any other form group.

something like:

function allOrNoneRequired(): ValidatorFn {
  return (ctrl: AbstractControl): ValidationErrors | null => {
    const fg = ctrl as FormGroup;
    const controls = Object.values(fg.controls);
    return (controls.every(fc => !fc.value) || controls.every(fc => !!fc.value))  
             ? null 
             : {allOrNoneRequired: true};
  };
}

then

this.myFormGroup = this.formBuilder.group({ 
                     ... my group info ... 
                   }, {validators: [allOrNoneRequired()]);


https://stackoverflow.com/questions/56995560/adding-custom-validator-to-whole-form-group-in-angular-reactive-from

No comments:

Post a Comment