如何在Angular中借助rxweb验证formArray内的重复OwnerId值
Angular FormArray OwnerId字段重复校验实现方案
无第三方依赖实现方案(更稳定)
无需引入额外库,通过自定义校验器实现重复校验:
- 定义FormArray全局重复校验函数
// 校验FormArray中所有ownerId是否重复 function uniqueOwnerIdValidator(formArray: FormArray): ValidationErrors | null { const ownerIds = formArray.controls .map(group => group.get('ownerId')?.value) .filter(val => val != null && val !== ''); // 利用Set去重后长度对比判断是否有重复 const hasDuplicate = new Set(ownerIds).size !== ownerIds.length; if (hasDuplicate) { // 给重复的对应ownerId控件设置错误标记 formArray.controls.forEach(group => { const ownerIdControl = group.get('ownerId'); const currentVal = ownerIdControl?.value; if (!currentVal) return; const repeatCount = ownerIds.filter(id => id === currentVal).length; if (repeatCount > 1) { ownerIdControl.setErrors({ ...ownerIdControl.errors, duplicateOwnerId: true }); } else if (ownerIdControl.hasError('duplicateOwnerId')) { // 无重复时清除对应错误标记 const errors = ownerIdControl.errors; delete errors.duplicateOwnerId; ownerIdControl.setErrors(Object.keys(errors).length ? errors : null); } }); return { duplicateOwnerId: true }; } return null; }
- 给FormArray绑定校验器
在初始化nameDriver这个FormArray时传入上述校验函数:
// 示例初始化代码,可结合你的实际写法调整 this.nameDriver = new FormArray([], uniqueOwnerIdValidator);
- 同步校验触发逻辑
修改createDriver方法,监听每个ownerId字段的变化,触发整个FormArray的重新校验:
createDriver () { const driverGroup = new FormGroup({ name: new FormControl(null, Validators.required), ownerId: new FormControl(null, Validators.required) }); // ownerId值变动时触发FormArray全局校验 driverGroup.get('ownerId')?.valueChanges.subscribe(() => { this.nameDriver.updateValueAndValidity(); }); return driverGroup; }
- 页面添加错误提示
在HTML的ownerId输入框下方添加错误提示:
<input class="form-control" type="text" id="ownerId" name="ownerId{{i}}" inputmode="numeric" dashFormat formControlName="ownerId" maxLength="14"> <!-- 新增错误提示 --> <div *ngIf="driver.get('ownerId')?.errors?.duplicateOwnerId" class="text-danger mt-1"> Owner Id不可重复 </div>
@rxweb/reactive-form-validators 不生效修复方案
如果要继续使用该第三方库,检查以下配置是否正确:
- 首先确保在对应模块中导入了
RxReactiveFormsModule - 给ownerId字段正确添加unique校验规则,指定对比的FormArray实例:
import { RxwebValidators } from '@rxweb/reactive-form-validators'; createDriver () { return new FormGroup({ name: new FormControl(null, Validators.required), ownerId: new FormControl(null, [ Validators.required, RxwebValidators.unique({ fieldName: 'ownerId', array: this.nameDriver }) ]) }) }
内容的提问来源于stack exchange,提问作者Fash
相关产品推荐
相关产品推荐

