在我的组件中,我有 2 个日期选择器,并且有开始日期和结束日期验证。此方法检查开始日期是否早于结束日期。此验证将适用于所有日期选择器。如何在其他组件中重用验证,而不是在其他组件中一次又一次地编写相同的逻辑。
搜索订单.ts
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 });
}
searchOrder.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>