反应形式自定义验证器不显示 angular6 中的错误

reactive form custom validators not displaying the error in angular6

在这个演示中,我为自定义验证器创建了一个示例表单, 在这里我有开始日期和结束日期以及时间和结束时间, 工作正常: 对于起始日期和截止日期验证工作正常并显示错误消息。

问题: 当 选择相同的日期时,例如)2018 年 7 月 21 日作为开始日期并且在 To date 和 In from Time 中相同 4:00 Am 和 To Time 3:00AM, 条件满足了,但是没有报错 message.Somethis 执行出错了,谁能帮我解决一下 appreciated

在 html 中,我提供了验证消息,但未显示。

To Time:
<input type="time" formControlName="ToTime">
    <mat-error *ngIf="DaterForm.get('ToTime').hasError('InValidToTime')">FromTime Should be less than ToTime if choose a same date</mat-error>

在组件中:

 DaterForm : FormGroup;

constructor(private fb:FormBuilder){
}
   ngOnInit(){

 this.DaterForm = this.fb.group(
{
  FromDate:['',[AppCustomDirective.fromDateValidator]], // validation working fine
  FromTime:[''],
  ToDate:['',[AppCustomDirective.ToDateValidator]],// validation working fine
  ToTime:['']
},{validator:[AppCustomDirective.timeValidator] // validation not working
}

自定义验证:

import { AbstractControl, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';

export class AppCustomDirective extends Validators{

   static fromDateValidator(fdValue: FormControl) {
    const date = fdValue.value;
    console.log('x');
    if (date ===null || date==='') return { requiredFromDate: true };

  }

   static ToDateValidator(todValue: FormControl) {
    const date = todValue.value;

    if (date ===null || date==='') return { requiredToDate: true };

  }


  static timeValidator(formGroupValues: FormGroup): any {
    debugger;
    console.log(formGroupValues);
    const FromDate = formGroupValues.get('FromDate').value;
    const ToDate = formGroupValues.get('ToDate').value;
    const FromTime = formGroupValues.get('FromTime').value;
    const ToTime = formGroupValues.get('ToTime').value;

    if (FromDate.toString() === ToDate.toString()) {
      let fromTime = [];
      let toTime = [];
      fromTime = FromTime.split(':');
      toTime = ToTime.split(':');
      if (parseInt(fromTime[0]) > parseInt(toTime[0])){
      alert("condition satisfied not return any error message");
         return { InValidToTime: true };
        }
      else if (
        parseInt(fromTime[0]) === parseInt(toTime[0]) &&
        parseInt(fromTime[1]) > parseInt(toTime[1])
      ){  alert("condition satisfied not return any error message")
        return { InValidToTime: true };
      }
    }
  }
}

live demo

这是因为您在 表单 上设置了错误,而您期望错误出现在特定输入上。

更改为 <mat-error *ngIf="DaterForm.hasError('InValidToTime')"> 解决了问题。

仅供参考,这不是 mat-error 设计用于 <input matInput/>

的方式

https://stackblitz.com/edit/angular-customvalidator-1fu5vx?file=app/datepicker-overview-example.html