【问题标题】:validating and display error messages for specific form controller in a form array angular验证并显示表单数组中特定表单控制器的错误消息
【发布时间】:2019-06-13 17:05:57
【问题描述】:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators, ValidatorFn, AbstractControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.buildForm();
  }
  get vehicleGroup(): FormArray {
    return <FormArray>this.myForm.get('vehicleGroup');
  }

  buildForm(): void {
    this.myForm = this.fb.group({
      name: ['', Validators.required],
      vehicleGroup: this.fb.array([
        this.fb.group({
          vehicle: ['', Validators.required]
        })
      ], [Validators.required]),
    });
  }

  addVehicles(): void{
    const itemToAdd = this.fb.group({
      vehicle: ['', Validators.required]
    });
    this.vehicleGroup.push(itemToAdd);
  }
  deleteVehicle(i: number){
    this.vehicleGroup.removeAt(i);
  }

  save(): void{
    console.log('save');
  }
}
<form novalidate (ngSubmit)="save()" [formGroup]="myForm">

  <div class="form-group">
    <label for="name">Name</label>
    <input id="name" type="text" formControlName="name">
  </div>

	<div class="form-group">
		<label for="vehicle">Vehicle</label>
      <div formArrayName="vehicleGroup" *ngFor="let vehicle of vehicleGroup.controls; let i=index">
        <div class="form-group" [formGroupName]="i">
          <div>
            <input id="{{'vehicle'+i}}" type="text" formControlName="vehicle">
            <button type="button" (click)="deleteVehicle(i)"
              *ngIf="vehicleGroup.length >= 2">remove
            </button>                  
          </div>
        </div>
      </div>
      <div class="form-group">
      <button type="button" class="link-button" [disabled]="!vehicleGroup.valid" (click)="addVehicles()">
          + Add more vehicles
      </button>
      </div>
	</div> 
</form> 

我有这个(stackBlitz) 用角度formBuilder 创建的简单表单

我只需要如何验证动态formArray 的每个元素,并在该特定字段无效时为每个元素显示唯一消息。 我尝试了几种解决方案,还尝试了custom validator function,返回ValidatorFn。有了它,我可以简单地验证formArray,但这对于我的场景来说还不够好,而且我仍然无法根据验证函数的行为显示消息。如何缩小范围,我只需要知道是否有更好的方法来验证这个formArray 的每个动态元素。这些是验证规则。

  1. 每个字段值都应该是唯一的。
  2. 需要实时验证
  3. 在添加了一些元素之后,有人编辑了之前添加的字段,它也应该与所有其他字段值实时验证(这是我被打动的地方,我可以从编辑字段向上验证,但不能从下面的字段相应地验证编辑字段)

如果有人可以向我展示一些以正确的方式实现这一目标的方法,那将是非常棒的,因为我已经被这个困扰了将近 3 天,但仍然无法找到更好的解决方案。

【问题讨论】:

  • 您的 stackblitz 演示无法正常工作
  • @yougeen 我会用我的component.tstemplate 更新问题
  • 你能在控制台中发布错误吗?
  • @RonakKhangaonkar 不,那里没有错误,我只需要一种方法来验证动态添加的formControlformArray,每个实时并在元素下方显示一条消息有错误。
  • 编辑了 StckBlitz 演示,现在可以使用了

标签: javascript validation angular6 angular-reactive-forms


【解决方案1】:

我在我的项目中使用了 @rxweb/reactive-form-validators 的唯一验证器。它可以直接在组件中使用,无需创建任何自定义验证函数。

您可以按如下方式编辑您的 addVehicles 方法:

addVehicles(): void{
    const itemToAdd = this.fb.group({
      vehicle: ['', RxwebValidators.unique()]
    });
    this.vehicleGroup.push(itemToAdd);
  }

并添加

ReactiveFormConfig.set({"validationMessage":{"unique":"Enter unique value in the input"}});

到 ngOnInit。

这里是forked stackblitz

【讨论】:

  • 这太好了,我之前没有在这里提到RxwebValidators。必须深入挖掘。非常感谢
猜你喜欢
  • 2018-12-16
  • 2022-11-09
  • 2019-06-11
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
相关资源
最近更新 更多