簡體   English   中英

Angular 自定義驗證器在值為 null 時返回 FormControl

[英]Angular custom validator returning the FormControl when value is null

我有一個使用自定義驗證器的 Angular 反應式表單組。 我正在使用 2 個日期選擇器,並想確認用戶是否從 1 中選擇一個日期,他們必須從另一個日期選擇 select。 由於 null 檢查,我在執行此操作時遇到問題。 所以在我的測試中,我只是填寫了第一個日期選擇器,而第二個保持不變——但這會導致奇怪的問題。 未填寫的表單控件有一個值: null 但是當我控制台記錄該值時,我將取回 formControl

this.form = this.fb.group({
      reservationNumber: this.fb.control(null),
      reservationName: this.fb.control(null),
      dateGroup: this.fb.group(
        {
          beginDate: [this.fb.control(null)],
          endDate: [this.fb.control(null)],
        },
        { validators: checkIfEndDateAfterStartDate }
      ),
      organizationName: this.fb.control(null),
      firstName: this.fb.control(null),
      lastName: this.fb.control(null),
   
    });
  }

這是我的自定義驗證器

export function checkIfEndDateAfterStartDate(
  c: AbstractControl
): { [key: string]: boolean } | null {
  const beginDateControl = c.get('beginDate');
  const endDateControl = c.get('endDate');

  //safety check
  if (beginDateControl?.pristine && endDateControl?.pristine) {
    return null;
  }

  **console.log(endDateControl?.value);** // this console logs the actual form control so on null checks it comes back as Valid. The form control object though in console log has the value as null

  if (
    (beginDateControl?.value && !endDateControl?.value) 
  ) {
//never hits because of above
    return { datesInvalid: true };
  }

  return null;
}

您在使用 formBuilder 初始化表單時出錯

嘗試改變這種方式。

this.form = this.fb.group({
          reservationNumber: [],
          reservationName: []
          dateGroup: this.fb.group(
            {
              beginDate: [],
              endDate: [],
            },
            { validators: checkIfEndDateAfterStartDate }
          ),
          organizationName: []
          firstName:[]
          lastName:  []
       
        });
    

暫無
暫無

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

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