簡體   English   中英

驗證並顯示特定消息的錯誤消息,形式為角數組

[英]validating and display error messages for specific form controller in a form array angular

 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> 

我有這個用角formBuilder創建的(stackBlitz)簡單表單

我簡單地需要如何驗證動態formArray每個元素,並在該特定字段無效的情況下為每個元素顯示唯一的消息。 我嘗試了幾種解決方案,還嘗試了帶有返回ValidatorFn custom validator function 這樣我就可以簡單地驗證formArray ,但是對於我的場景而言還不夠好,但是仍然無法根據驗證函數的行為顯示消息。 如何縮小范圍,我只需要知道是否有更好的方法來驗證此formArray每個動態元素。 這些是驗證規則。

  1. 每個字段的值都應該是唯一的。
  2. 需要實時驗證
  3. 添加少量元素后,有人編輯先前添加的字段,還應使用其他所有字段值進行實時驗證(這是我被打到的地方,我可以從編輯字段進行向上驗證,但不能修改編輯字段下方的字段經過相應驗證)

如果有人可以向我展示以正確的方式實現這一目標的方法,那將是非常不錯的,因為我已經為之震驚了近三天,但仍然找不到更好的解決方案。

我在項目中使用了@rxweb/reactive-form-validators唯一驗證@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。

這是分叉的閃電戰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM