无法以角度读取 null 的属性“valideDate”

时间:2021-07-05 07:59:17

标签: angular validation

我正在尝试为日期和时间添加一些验证。

  1. 日期必须小于当前日期。
  2. 开始时间必须小于结束时间。
  3. 如果日期等于当前日期的开始时间和结束时间,则每个时间都必须小于当前时间。

首先,我只尝试小于当前日期的案例编号 (1) 日期。

这是我的代码:

我在 mat-dialog 3 输入(日期、开始时间、结束时间):

<ng-template #callAPIDialog>
  <form [formGroup]="rangeForm">


    
    <div style="padding: 10px;">
      <div class="form-group">
        <label>Date</label>
        <input
          type="date"
          class="form-control"
          style="cursor: pointer; padding-left: 1rem;"
          formControlName="date"
        />
        <div *ngIf="date.errors.valideDate">
          Errors
        </div>
      </div>

      <div class="form-group">
        <label>Start Time</label>
        <input
          type="time"
          class="form-control"
          style="cursor: pointer; padding-left: 1rem;"
          formControlName="startTime"
        />
      </div>
      <div class="form-group">
        <label>End Time</label>
        <input
          type="time"
          class="form-control"
          style="cursor: pointer; padding-left: 1rem;"
          formControlName="endTime"
        />
      </div>
      <br>
      <div align="end" style="text-align: center;
      ">

        <button style="margin-right: 10px;" class="btn btn-primary" mat-button matDialogClose="cancel">
            Cancel
        </button>
        <button mat-button matDialogClose="submit" class="btn btn-danger" [disabled]="!rangeForm.valid"
        style="cursor: pointer;">
            Submit
        </button>

    </div>

    </div>
  </form>
</ng-template>

在 component.ts 中:

  this.rangeForm = new FormGroup({
    date: new FormControl(this.dateDialog, [Validators.required, ValidatorsSettings.valideDate]),
    startTime: new FormControl(starttime, Validators.required),
    endTime: new FormControl(endtime, Validators.required),
    
  },);

  let dialogRef = this.dialog.open(this.callAPIDialog);
  dialogRef.afterClosed().subscribe((result) => {
  // Note: If the user clicks outside the dialog or presses the escape key, there'll be no result
  if (result !== undefined) {

    if (result === "submit") {
      if(this.rangeForm.valid){
        this.historyDateHanlder.changeHistoryDate(this.rangeForm.value);
    
        this.router.navigate([....]);
  
      }
  
    } else if (result === "cancel") {
    }
  }
  });

在validaDate方法的情况下:

  static valideDate(control: FormControl) : ValidationErrors {
    var currentDate = new Date();

    if ((control.value < = currentDate.getTime())) {
        // invalid, return error object
        return { 'valideDate' : true } ;

    }
     else {
       // valid, return null
       return null ;
     }
  }

但不起作用我收到此错误:

ERROR TypeError: Cannot read property 'valideDate' of null
    at ...

0 个答案:

没有答案