You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular响应式表单如何检测FormGroups中attributeDisplayName字段重复值

解决方案

1. 修改提交前的校验逻辑

替换你原有遍历FormArray的代码即可,同时会自动给重复字段标记错误状态:

const displayNameSet = new Set();
let hasDuplicate = false;
const itemFormArray = this.formGroups.get('items') as FormArray;

itemFormArray.controls.forEach((item) => {
  const currentName = item.value.attributeDisplayName?.trim();
  // 空值会被原有必填校验拦截,此处直接跳过
  if (!currentName) return;

  if (displayNameSet.has(currentName)) {
    hasDuplicate = true;
    // 给重复字段添加自定义错误标记
    item.get('attributeDisplayName')?.setErrors({ duplicate: true });
  } else {
    displayNameSet.add(currentName);
    // 清理之前误加的重复错误标记
    const nameControl = item.get('attributeDisplayName');
    if (nameControl?.hasError('duplicate')) {
      delete nameControl.errors['duplicate'];
      nameControl.updateValueAndValidity({ onlySelf: true });
    }
  }
});

if (hasDuplicate) {
  // 此处替换为你项目中使用的提示组件,比如Kendo Dialog
  alert('CUSTOM FIELD LABEL 字段存在重复值,请修改后再提交');
  return; // 直接终止后续提交逻辑
}

// 无重复时执行你的原有提交逻辑

2. 调整前端错误提示模板

修改Kendo Grid列模板的错误提示部分,增加重复错误的展示:

<kendo-grid-column field="attributeDisplayName" title="CUSTOM FIELD LABEL" width="190">  
  <ng-template kendoGridEditTemplate let-column="column" let-formGroup="formGroup" >          
    <input ngDefaultControl  class="k-textbox" [formControl]="formGroup.get(column.field)">
    
    <div *ngIf="formGroup.get(column.field).errors && (formGroup.get(column.field).dirty || formGroup.get(column.field).touched)">
          <span style="color:red" class="k-icon k-i-warning"></span>
          <span style="color:red" *ngIf="formGroup.get(column.field).errors.required">CUSTOM FIELD LABEL is a required field</span>
          <span style="color:red" *ngIf="formGroup.get(column.field).errors.duplicate">CUSTOM FIELD LABEL 不能重复</span>
    </div>

  </ng-template>
</kendo-grid-column>

补充说明

  • 代码中对字段值做了trim()处理,避免首尾空格导致的假重复,不需要可以删除该方法
  • 若需要实现边输入边校验重复,可给FormArray添加全局自定义校验器,提交前校验的场景以上方案完全满足
  • 重复字段会单独标记错误状态,用户可以直接定位到重复的行,无需自己查找

内容的提问来源于stack exchange,提问作者vamsi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:45:10