I am implementing ngx-bootstrap datepicker in Angular-14. Then I want to validate between IssuedDate and ExpiryDate of Drivers Licence.
I have this code.
component.ts:
minIssuedDate!: Date;
minExpiryDate!: Date;
constructor(
private fb: FormBuilder
) {
this.minIssuedDate = new Date();
this.minExpiryDate = new Date();
this.minIssuedDate.setDate(this.minIssuedDate.getDate());
this.minExpiryDate.setDate(this.minExpiryDate.getDate() 1);
}
createProfile() {
this.createProfileForm = this.fb.group({
issuedDate: ['', [Validators.required],
expiryDate: ['', [Validators.required]]
});
}
ngOnInit(): void {
this.createProfile();
}
component.html:
<div >
<div >
<div >
<label for="issuedDate">Issued Date</label>
<div >
<div >
<span ><i ></i></span>
</div>
<input type="text"
placeholder="DD-MM-YYYY"
formControlName='issuedDate'
bsDatepicker
[minDate]="minIssuedDate"
[bsConfig]="{ isAnimated: true, dateInputFormat: 'DD-MM-YYYY', returnFocusToInput: true, showClearButton: true, clearPosition: 'right' }">
</div>
<div *ngIf="fc['issuedDate'].touched && fc['issuedDate'].invalid" >
<div *ngIf="fc['issuedDate'].errors && fc['issuedDate'].errors['required']">Issued Date field is required!</div>
</div>
</div>
</div>
<div >
<div >
<label for="expiryDate">Expiry Date<span style="color:red;">*</span></label>
<div >
<div >
<span ><i ></i></span>
</div>
<input type="text"
placeholder="DD-MM-YYYY"
formControlName='expiryDate'
bsDatepicker
[minDate]="minExpiryDate"
[bsConfig]="{ isAnimated: true, dateInputFormat: 'DD-MM-YYYY', returnFocusToInput: true, showClearButton: true, clearPosition: 'right' }">
</div>
<div *ngIf="fc['expiryDate'].touched && fc['expiryDate'].invalid" >
<div *ngIf="fc['expiryDate'].errors && fc['expiryDate'].errors['required']">Expiry Date field is required!</div>
</div>
</div>
</div>
</div>
How do I validate that issuedDate must not be greater than ExpiryDate?
Thanks
CodePudding user response:
You can create a custom validator and apply it to createProfileForm
Ts
createProfile() {
this.createProfileForm = this.fb.group(
{
issuedDate: ['', [Validators.required]],
expiryDate: ['', [Validators.required]],
},
{ validators: this.dateValidator }
);
}
dateValidator(group: FormGroup): ValidationErrors | null {
const fromCtrl = group.get('issuedDate')!;
const toCtrl = group.get('expiryDate')!;
return new Date(fromCtrl.value) > new Date(toCtrl.value)
? { issueDateGreater: 'issue date is greater than expiry date' }
: null;
}
Html
<span *ngIf="createProfileForm!.hasError('issueDateGreater')">issue date is greater than expiry date</span>