How to add custom validator to a FormArray?

喜夏-厌秋 提交于 2020-03-05 02:59:40

问题


I want to add custom validator to form in order to prevent mat-step switching to next step. All works well when I use FormGroups but I fail to achieve validation when I have to use FormArray.

I've tried at least two variants of assigning validator on form initialization:

  • inside array

statuses: this._formBuilder.array([this.createStatus()], defaultStatusValidator())

  • inside parent form of array

this.productionLineStatuses = this._formBuilder.group({statuses: this._formBuilder.array([this.createStatus()])}, {validator: defaultStatusValidator()});

But this attempts are causing error (probably when casting validator):

TypeError: Cannot convert undefined or null to object 
    at Function.keys (<anonymous>)
    at FormGroup.validate [as validator] (default-status.directive.ts:6)
    at FormGroup._runValidator (forms.js:3438)
    at FormGroup.updateValueAndValidity (forms.js:3399)
    at new FormGroup (forms.js:4097)
    at FormBuilder.group (forms.js:7578)
    at CreateProductionLineComponent.ngOnInit (create-production-line.component.ts:31)

In the following case error is not thrown, but validator is not working too. Here is rest of my code and my custom validator:

ngOnInit() {
    this.productionLineDetails = this._formBuilder.group({
      productType: ['', Validators.required],
      language: ['', Validators.required],
      name: ['', Validators.required],
      description: [''],
    });
    this.productionLineStatuses = this._formBuilder.group({
      statuses: this._formBuilder.array([
        this.createStatus()
      ])
    }, defaultStatusValidator());
    this.statuses = this.productionLineStatuses.get('statuses') as FormArray;
    this.statusError = false;
  }

validator:

export function defaultStatusValidator(): ValidatorFn {
    return function validate (statuses: FormArray) {
    let defaultCounter = 0;
    Object.keys(statuses.value.controls).forEach(key => {
        const control = statuses.value.controls[key];

        if (control.value.default == true) {
            defaultCounter ++;
        }
      });
    return (defaultCounter > 1) ? {moreThanOneStatusIsDefault: true} : null;
    };
}

How should I properly add validator to FormArray?


回答1:


You has consider if your FormArray is a FormArray of FormControls or a FormArray of FormGroups, but the problem is how you iterate over the controls,

A simple example of both

export function customValidateArray(): ValidatorFn {
    return (formArray:FormArray):{[key: string]: any} | null=>{
      let valid:boolean=true;
      formArray.controls.forEach((x:FormControl)=>{
          valid=valid && x.value=="a"
      })
      return valid?null:{error:'Not all a'}
    }
  };

export function customValidateArrayGroup(): ValidatorFn {
    return (formArray:FormArray):{[key: string]: any} | null=>{
      let valid:boolean=true;
      formArray.controls.forEach((x:FormGroup)=>{
          valid=valid && x.value.name=="a" 
      })
      return valid?null:{error:'Not all name are a'}
    }
  };

You can see an example in stackblitz

NOTE: To create the form, I use the constructor of FormGroup, FormControl and FormArray, but you can use FormBuilder too.

NOTE 2: it's not necesary enclose a FormArray in a FormGroup



来源:https://stackoverflow.com/questions/57794118/how-to-add-custom-validator-to-a-formarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!