簡體   English   中英

自定義反應式表單驗證器中的多個角度錯誤

[英]Angular multiple errors in custom reactive form validator

我正在驗證呼叫中心的表單,其中通常會按特定順序填寫字段。 如果用戶跳過,我想為多個字段引發錯誤。 我發現以下有效:

  export const recordValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {

    if(!firstField.value && !secondField.Value && !thirdField.value)    
    {
      firstField.setErrors({ "firstFieldError" : true});
      secondField.setErrors({ "secondFieldError" : true});

      return {"firstFieldError" : true, "secondFieldError" : true};

    }
  }

而且 firstField 和 secondField 都正確顯示錯誤。

現在根據文檔ValidationErrors 只是錯誤的映射。 但它顯然沒有任何方法,所以我想我只是將現有的映射轉換為 ValidationErrors 並返回:

  export const recordValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {

    if(!firstField.value && !secondField.Value && !thirdField.value)    
    {
      firstField.setErrors({ "firstFieldError" : true});
      secondField.setErrors({ "secondFieldError" : true});

      let errorMap = new Map();

      errorMap.set("firstFieldError",true);
      errorMap.set("secondFieldError",true);

      let errorValidators:ValidationErrors = errorMap;

      return errorValidators;

    }
  }

但它不會引發任何錯誤。

我的模板如下所示:

<mat-form-field>
  <input formControlName="firstField" type="datetime-local" placeholder="First Field" [errorStateMatcher]="errorMatcher" matInput>                        
      <mat-error *ngIf="Form.errors?.firstFieldError">
      First field error!
      </mat-error>
</mat-form-field>

誰能幫我看看為什么第一個有效而第二個無效

吉姆,自定義驗證器不像你說的那樣工作。 您需要返回一個對象(或 null)。 所以你的驗證必須喜歡一些

export const recordValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
    let invalid=false
    const error={}
    if (!control.value.firstField && control.value.secondField)
    {
        error.firstFieldError=true;
        invalid=true;
    }
    if (!control.value.secondField && control.value.thirdField)
    {
        error.secondFieldError=true;
        invalid=true;
    }
    return invalid?error:null;
  }

看看我們如何從“控件”中獲取價值——它是 formGroup——以及我們如何創建一個具有一兩個屬性的對象——如果你寫檢查,你可以在你的 .html 中看到——

{{form.errors|json}}

注意:我真的不理解您的驗證器,並想象有人會考慮您問題中的描述

這篇博客和 angular.io 的參考的幫助下,我需要回到這個問題並設法正確解決它。

這是一個返回驗證錯誤映射的驗證器:

import { Injectable } from '@angular/core';
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

@Injectable({ providedIn: 'root' })
export class ShiftTimeValidator {
    constructor() {}

    //validate(time: string, shifts: VehicleShift[]): ValidatorFn {
    validate(): ValidatorFn {

        return (
            control: AbstractControl,
        ): ValidationErrors => {

            let errors:ValidationErrors = {};

            // If the form hasn't been touched then don't validate
            if (control.pristine) {
                null;
            }

            // Check if the time falls inside any existing shifts
            if(1 == 1){
                errors["inside-other-shift"] = true;
            }

            // If the time is the start time, then check that it's before the end time
            if(1 == 1){
                errors["start-before-end"] = true;
            }

            // If the time is an end time, check that it's after the start time.
            if(1 == 1){
                errors["end-before-start"] = true;
            }

            // If the this time has an existing match, check that the new shift doesn't overlap any other shifts.
            if(1 == 1){
                errors["shift-overlap"] = true;
            }

            console.log(errors);


            return errors;
        };
    }
}

以下是將驗證器添加到表單的方法:

return this.fb.group({
  vehicleShiftId: [],
  vehicleId: [this.vehicle.vehicleId, Validators.required],
  shiftStartTimeString: [, [Validators.required, this.shiftValidator.validate()]],
  shiftEndTimeString: [, Validators.required, this.shiftValidator.validate()],
  vehicleStaff: staffArray
});

以下是顯示錯誤消息的方法:

<mat-form-field>
    <input formControlName="shiftStartTimeString" type="time"
    name="shiftStartTime"
    placeholder="Shift start time" [errorStateMatcher]="errorMatcher" matInput>

        <mat-error *ngIf="shiftStartTime?.hasError('inside-other-shift')">
        Shift start time is inside another shift.
        </mat-error>

        <mat-error *ngIf="shiftStartTime?.hasError('start-before-end')">
        Shift start time is after shift end time.
        </mat-error>

        <mat-error *ngIf="shiftStartTime?.hasError('end-before-start')">
        Shift end time is before shift start time.
        </mat-error>

        <mat-error *ngIf="shiftStartTime?.hasError('shift-overlap')">
        This shift overlaps another shift.
        </mat-error>
</mat-form-field>

您是否應該這樣做以支持為您嘗試驗證的每件事創建單獨的驗證器可能有待討論,但這證明可以從單個驗證器正確返回多個錯誤。

暫無
暫無

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

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