垫日期开始日期结束日期验证angular 8

Mat date start date end date validation angular 8

我正在使用 Mat 日期选择器,其中我有开始日期和结束日期,我有一个验证,例如结束日期不应小于开始日期

如果开始日期是 2020 年 1 月 12 日,结束日期可以是 2020 年 1 月 12 日或更晚,但不能是 2020 年 1 月 11 日。

目前我正在尝试使用 Min MAX,但这没有按预期工作

我在 google 中尝试,所以没有正确

   <mat-form-field>
      <input matInput [matDatepicker]="fromDate" placeholder="Choose a date"
          [value]="getData(item2.firstPatientInDate)" [max]="today<item2.lastPatientInDate|| item2.lastPatientInDate == undefined?today:item2.lastPatientInDate" [(ngModel)]="item2.firstPatientInDate">
                    <mat-datepicker-toggle matSuffix [for]="pickerstart"></mat-datepicker-toggle>
                    <mat-datepicker #picker></mat-datepicker>
                </mat-form-field>

        <mat-form-field>
           <input matInput [matDatepicker]="pickerend" [max]="today" [min]="item2.firstPatientInDate"   placeholder="Choose a date"
                        [value]="getData(item2.lastPatientInDate)" [(ngModel)]="item2.lastPatientInDate">
                    <mat-datepicker-toggle matSuffix [for]="pickerend"></mat-datepicker-toggle>
                    <mat-datepicker #picker1></mat-datepicker>

                </mat-form-field>

将这种方式用于带有自定义验证的反应式表单

constructor(private formBuilder: FormBuilder) { 
   this.yourForm = this.formBuilder.group({
   startDate: [''],
   endDate: ['']
   }, {validator: this.checkDates});  
}

checkDates(group: FormGroup) {
   if(group.controls.endDate.value < group.controls.startDate.value) {
   return { notValid:true }
   }
   return null;
}

在你的前端

<small *ngIf="yourForm.hasError('notValid')">Not valid</small>

您可以在下面找到工作示例 link:

stackblitz: angular material start-end date sample

TypeScript file

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

@Component({
  selector: 'datepicker-value-example',
  templateUrl: 'datepicker-value-example.html',
  styleUrls: ['datepicker-value-example.css'],
})
export class DatepickerValueExample {
  startDate = new FormControl(new Date());
  endDate = new FormControl(new Date());
}

HTML file

<mat-form-field>
  <input matInput [matDatepicker]="picker1" placeholder="Start Date" [formControl]="startDate">
  <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
  <mat-datepicker #picker1></mat-datepicker>
</mat-form-field>

<mat-form-field>
  <input matInput [matDatepicker]="picker2" placeholder="End Date"
   [min]="startDate.value" [formControl]="endDate">
  <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
  <mat-datepicker #picker2></mat-datepicker>
</mat-form-field>

尝试这种方式进行自定义日期范围验证

在 HTML 代码中,如您在 (dateChange) 事件中所见。我创建了 comparisonStartdateValidator 和 comparisonEnddateValidator 方法来验证输入的日期范围。

HTML 文件

  <mat-form-field appearance="outline">
    <mat-label> Covering Start Date </mat-label>
    <input
      matInput
      [matDatepicker]="CovStartdate"
      formControlName="covstartdate"
      (dateChange)="comparisonStartdateValidator()"
      required
    />
    <mat-datepicker-toggle
      matSuffix
      [for]="CovStartdate"
    ></mat-datepicker-toggle>
    <mat-datepicker #CovStartdate></mat-datepicker>
    <mat-error
      *ngIf="
        formGroup.controls['covstartdate'].hasError('invaliddaterange')
      "
    >
      <strong>Start date cannot be greater than end date</strong>
    </mat-error>
    <mat-error
      *ngIf="formGroup.controls['covstartdate'].hasError('required')"
    >
      Covering Start date is <strong>required</strong>
    </mat-error>
  </mat-form-field>

  <mat-form-field appearance="outline">
    <mat-label> Covering End Date </mat-label>
    <input
      matInput
      [matDatepicker]="CovEnddate"
      formControlName="covenddate"
      (dateChange)="comparisonEnddateValidator()"
      required
    />
    <mat-datepicker-toggle
      matSuffix
      [for]="CovEnddate"
    ></mat-datepicker-toggle>
    <mat-datepicker #CovEnddate></mat-datepicker>
    <mat-error
      *ngIf="formGroup.controls['covenddate'].hasError('invaliddaterange')"
    >
      <strong>End date cannot be earlier than start date</strong>
    </mat-error>
    <mat-error
      *ngIf="formGroup.controls['covenddate'].hasError('required')"
    >
      Covering End date is <strong>required</strong>
    </mat-error>
  </mat-form-field>
</div>

Date range pic initial

TS文件

在 TS 代码中,您可以在下面使用我自定义的验证。 comparisonEnddateValidator 方法验证结束日期,而 comparisonStart dateValidator 方法验证开始日期。

   constructor() { 
     formGroup: FormGroup = new FormGroup({
       covenddate: new FormControl(),
       covstartdate: new FormControl()
     });
   }

  comparisonEnddateValidator(): any {
    let ldStartDate = this.formGroup.value['covstartdate'];
    let ldEndDate = this.formGroup.value['covenddate'];

    let startnew = new Date(ldStartDate);
    let endnew = new Date(ldEndDate);
    if (startnew > endnew) {
      return this.formGroup.controls['covenddate'].setErrors({ 'invaliddaterange': true });
    }

    let oldvalue = startnew;
    this.formGroup.controls['covstartdate'].reset();
    this.formGroup.controls['covstartdate'].patchValue(oldvalue);
    return this.formGroup.controls['covstartdate'].setErrors({ 'invaliddaterange': false });
  }

  comparisonStartdateValidator(): any {
    let ldStartDate = this.formGroup.value['covstartdate'];
    let ldEndDate = this.formGroup.value['covenddate'];

    let startnew = new Date(ldStartDate);
    let endnew = new Date(ldEndDate);
    if (startnew > endnew) {
      return this.formGroup.controls['covstartdate'].setErrors({ 'invaliddaterange': true });
    }

    let oldvalue = endnew;
    this.formGroup.controls['covenddate'].reset();
    this.formGroup.controls['covenddate'].patchValue(oldvalue);
    return this.formGroup.controls['covenddate'].setErrors({ 'invaliddaterange': false });
  }

Start date picture error sample End date picture error sample