如何自定义验证 FormArray

How to custom validate FormArray

我正在使用 FormArray 构建一个响应式表单,其中包含 FormGroups。每个 FormGroup 有 3 个控件,其中两个是下拉列表。我想阻止用户在其中一个下拉菜单中多次选择相同的选项。我写了一个自定义验证器来实现这个。验证器似乎有效,因为我在 return { 'subCategoryRepetition': true } 处输入了 if 子句,但表单仍然有效,控件的错误数组为空。

在此先感谢您的帮助!

代码如下:

component.ts

initEditUserDetialsForm() {
   this.editUserDetailsForm = this.formBuilder.group({
   ...
      categories: this.formBuilder.array(this.initSavedCategoryArray(this.merchantUserDetails.categories),
      checkSubCategoryRepetition.bind(checkSubCategoryRepetition))
   });
   this.categories = this.editUserDetailsForm.get('categories') as FormArray;
   this.removeCategoryDisabled = this.categories.length < 2;
}

initSavedCategoryArray(categories: CategoryDTO[]): FormGroup[] {
    let formGroupArray: FormGroup[] = [];
    categories.forEach((category, index) => {
        if (this.subCategories.length === 0) {
             this.subCategories.push(category.subCategory.mainCategory.subCategories);
        } else {
             this.subCategories.splice(index, 1, category.subCategory.mainCategory.subCategories);
        }
        formGroupArray.push(
             this.formBuilder.group({
                 mainCategory: [+category.subCategory.mainCategory.mainCategoryId, Validators.required],
                 subCategory: [+category.subCategory.subCategoryId, Validators.required],
                 donationPercentage: [category.donationPercentage, [Validators.required, Validators.min(1), Validators.max(100)]]
             })
         );
     });
     return formGroupArray;
}

custom.validator.ts

export function checkSubCategoryRepetition(formArray: FormArray) {
    let subCategoryIds: number[] = [];
    formArray.controls.forEach((formGroup: FormGroup) => {
        if (subCategoryIds.includes(+formGroup.controls.subCategory.value)) {
            console.log('repetition')
            return { 'subCategoryRepetition': true };
        }
        subCategoryIds.push(+formGroup.controls.subCategory.value);
    });
    return null;
}

forEach inside return 不会中断函数执行,这就是为什么它不起作用,尝试使用 for 或 reduce 而不是 forEach。

试试这个:

export function checkSubCategoryRepetition(formArray: FormArray) {
    let subCategoryIds: number[] = [];
    const groups = formArray.controls;
    for(let i = 0; i < groups.length; i++){
      if (subCategoryIds.includes(+group[i].controls.subCategory.value)) {
            console.log('repetition')
            return { 'subCategoryRepetition': true };
        }
        subCategoryIds.push(+group[i].controls.subCategory.value);
    }
    return null;
}