Angular 2+ ReactiveForm自定义验证功能未触发

时间:2017-06-19 20:47:35

标签: angular angular-reactive-forms angular-validation

我正在以下列方式构建我的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]
});

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

1 个答案:

答案 0 :(得分:1)

FormBuilder.group方法有两个参数:

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

其中extra可以object,其属性为validator和/或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

找到实例