如何检查Angular5中以反应形式存在于表单数组中的重复formcontrol值?

时间:2018-08-29 05:43:44

标签: angular angular5 angular4-forms

我正在构建表单数组,如

    this.myForm= this.fb.group({
  codes: this.fb.array([])
 })

 this.codes =   this.myForm.controls['newChargecodes']

  this.codes.push(this.fb.group({
     chargeCode: ['', [Validators.required]],
  })


  addRow () {
   this.codes.push(this.fb.group({
     chargeCode: ['', [Validators.required]],
  })

  }

  Html

  <tr *ngFor="let code of myForm.get('codes').controls; let i = index;" 
              [formGroupName]="i">
               <td class="text-center">
                  <input class="form-control input-text text-center" pInputText type="text" placeholder="{{columns['chargeCode']}}" id="chargeCode"
                    formControlName="chargeCode" name="chargeCode">
                </td>
                <td>< a (click)="addRow()">+</a></td>
 </tr>

我要重复验证代码

例如用户输入

chargecode[0]-A1, -> true
 chargecode[1]-A2, -> true
 chargecode[2]-A1-> -> false->

当用户输入输入内容时,它将显示错误的重复收费代码

请帮助我如何为反应形式的表单数组编写自定义验证

3 个答案:

答案 0 :(得分:1)

以以下方式检查工作解决方案:

  

在此示例中验证重复人员的姓名。

DEMO

TS:

findDuplicate(name, p): boolean {
   let myArray = this.getPeople(this.myForm);

   let test = myArray.filter(data => data.controls.name.value == name && name != null)

   if (test.length > 1) {
      return true;
   } else {
     return false
 }}

HTML:

<form class="form-group" [formGroup]="myForm" (ngSubmit)="submit()">
    <table class="table" formArrayName="people">
        <thead class="thead bg-info">
            <tr>
                <th scope="col">People Name
                    <button (click)="addPeople()" type="button">+</button>
                </th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let person of getPeople(myForm); let i=index" [formGroupName]="i">
                <td><input class="form-control" type="text" placeholder="Name" formControlName="name">
                    <p style="color:red;" *ngIf="!findDuplicate(person, i) && i > 0">Duplicate Name </p>
                </td>
            </tr>
        </tbody>
    </table>
</form>

答案 1 :(得分:0)

您可以从这个想法中得到启发来解决类似的问题。文章: Custom Group Validation in Angular 2

有现场示例live example

谢谢

答案 2 :(得分:-2)

假设您要以这种形式比较两个输入值。在这种情况下,我具有密码和ConfirmPassword表单控件:

CREATE PROCEDURE [dbo].[GetItems] 
@IsInsert Bit = NULL
AS 
BEGIN 

SELECT * FROM [Table]
WHERE @IsInsert IS NULL OR IsInsert = @IsInsert 

END

passwordConfirmValidator是这样的函数:

  createForm(): void {
    this.registerForm = this.fb.group({
      password: ['', [Validators.required]],
      passwordConfirm: ['', [Validators.required, this.passwordConfirmValidator]]
    });
  }

如您所见,您可以通过root属性访问其他表单控件。