这是我的主要表单组:
this.mainForm = this.formBuilder.group({
productType1: new FormArray([], CustomValidators.minSelectedCheckboxes()),
productType2: new FormArray([],CustomValidators.minSelectedCheckboxes()),
productInput : ['', Validators.required],
productDetails : ['', Validators.required],
});
}
和 我的自定义验证功能是
static minSelectedCheckboxes(min: number = 1): ValidatorFn {
const result = (formArray: FormArray): { [key: string]: boolean } | null => {
const totalSelected = formArray.controls
// get a list of checkbox values (boolean)
.map((control) => control.value)
// total up the number of checked checkboxes
.reduce((prev, next) => next ? prev + next : prev, 0);
// if the total is not greater than the minimum, return the error message
return totalSelected >= min ? null : { required: true };
};
return result;
}
,并且我可以进行验证以获取至少一个复选框。 但是我的要求是从FormArrays productType1和productType2中至少选择一个复选框。
即productType1中是否有5个复选框 和5复选框位于productType2中 那么如果我从productType1或productType2中选择了复选框,我的验证就应该进行。
答案 0 :(得分:0)
表单组初始化
public static class Mapper
{
public static IEnumerable<ViewModel> ToViewModelList(this IEnumerable<Entity> entities)
{
return entities.Select(ToViewModel);
}
public static ViewModel ToViewModel(this Entity entity)
{
return new ViewModel() {
// Include mapping inside here
Id = entity.Id;
};
}
}
验证器功能
this.mainForm = this.formBuilder.group(
{
productType1: new FormArray([this.formBuilder.control(false)]),
productType2: new FormArray([this.formBuilder.control(false), this.formBuilder.control(false)]),
productInput : ['', Validators.required],
productDetails : ['', Validators.required]
},
{
validator: CustomValidators.minSelectedCheckboxes(['productType1', 'productType2'])
}
);