繁体   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