根据 rxweb Angular 中的 formArray 验证重复输入

Validate duplicate input based on formArray in Angular by rxweb

如何验证 formArray 中的重复项 OwnerId。我正在尝试安装这个 @rxweb/reactive-form-validators 但它不起作用。这是我的演示代码 Stackblitz

HTML:

<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 d-flex" [formGroupName]="i"
      *ngFor="let driver of nameDriverControl.controls; let i=index">
      <label>{{i+1}}.Name</label>
      <input class="form-control" type="text" id="name" name="name{{i}}"  formControlName="name" ><br/>
      <label>{{i+1}}.Owner Id</label>
      <input class="form-control" type="text" id="ownerId" name="ownerId{{i}}" inputmode="numeric" dashFormat formControlName="ownerId" maxLength="14">
      <div class="col-2 col-sm-2 col-md-2 col-lg-2 col-xl-2">
        <div class="form-group mb-0" *ngIf="i !== 0">

          <button class="btn btn-danger" (click)="removeDriver(i)">
      Delete
    </button>
        </div>
        <div class="form-group mb-2">

          <button *ngIf="i >= 0 && i < 1" type="button" [hidden]="nameDriver.length > 3" (click)="addDriver()" class="btn btn-primary">
      Add
    </button>
        </div>
      </div>
    </div>

组件

createDriver () {
    return new FormGroup({
      name: new FormControl(null, Validators.required),
      ownerId: new FormControl(null, Validators.required)
    })
  }

您可以使用 @rxweb/reactive-form-validators (2.1.3) 最新版本的 unique 验证器。

安装后你需要像这样导入@rxweb:

import { RxwebValidators } from '@rxweb/reactive-form-validators';

然后在您的 createDriver 方法中为 ownerId 添加 unique 验证器,如下所示:

createDriver () {
    return new FormGroup({
      name: new FormControl(null, Validators.required),
      ownerId: new FormControl("", RxwebValidators.unique(
        { message: 'You must enter a unique OwnerId' }
      ))
    })
}

并且在您的 HTML 模板中,您可以添加这样的错误消息:

<small class="form-text text-danger" *ngIf="driver.controls.ownerId.errors">{{driver.controls.ownerId.errors.unique.message}}<br/></small>  

这是我为您创建的工作示例:StackBlitzLink

结果:

有关 unique 验证的详细信息,请参阅 this