Angular 2+ ReactiveForm 自定义验证函数未触发

Angular 2+ ReactiveForm Custom Validation Function Not Triggered

我正在按照以下方式构建我的 FormGroup

this.datesGroup = this.fb.group({
  arrivalDate: [null, Validators.required],
  departureDate: [null, Validators.required]
}, (fg: FormGroup) => {
  console.log('validate');
  return moment.unix(fg.value.departureDate.epoc).diff(moment.unix(fg.value.arrivalDate.epoc)) > 0 ?
    null : {
      'departureBeforeArrival': true
    };
});
this.formGroup = this.fb.group({
  dates: this.datesGroup,
  accommodation: ['', Validators.required]
});

但是上面的验证箭头函数永远不会被触发;控制台从不记录。我做错了什么?

FormBuilder.group 方法有两个参数:

group(controlsConfig: {
        [key: string]: any;
    }, extra?: {
        [key: string]: any;
    } | null): FormGroup;

其中 extra 可以是 object 和 属性 validator and/or asyncValidator.

所以我会将您的代码更改为:

this.datesGroup = this.fb.group({
  arrivalDate: [null, Validators.required],
  departureDate: [null, Validators.required]
}, {
  validator: (fg: FormGroup) => {
    console.log('validate');
    return 1 > 0 ?
      null : {
        'departureBeforeArrival': true
      };
  }
});

可以在此处找到实际示例 https://plnkr.co/edit/BcExweMVcVxy1yKhwmJp?p=preview