Angular 7 Start Date End Date Validation

Angular 7 and 8 Validate Two Dates - Start Date & End Date

In this example, I am sharing “How to compare or validate two dates in Angular?” using custom validation function in Angular 7 and Angular 8.

Here, I’m validating the two dates  - a start date and end date. The end date should be greater than the Start date”.

Let’s see the example:-
import { Component, OnInit } from '@angular/core';
import { UserRequest } from '../model/user';

  selector: 'User_Cal',
  templateUrl: './usercal.component.html',
  styleUrls: ['./usercal.component.css']
export class UserCalComponent implements OnInit {
  constructor(private EncrDecr: EncrDecrService, private  httpHttpClient,
              private datePipe: DatePipe) {             
  //model class
  model = new UserRequest(null, null, null, null, null);

  //Error Display

  ngOnInit() { }

    this.model.StartDate = this.datePipe.transform(this.model.StartDate,"dd-MM-yyyy");
    this.model.EndDate = this.datePipe.transform(this.model.EndDate,"dd-MM-yyyy");  

    this.isValidDate = this.validateDates(this.model.StartDate, this.model.EndDate);
    if(this.isValidDate){<UserRequest>(environment.API_URL + "User/StEtDate", this.model, this.options)
          .subscribe(res => {
            err => {

  validateDates(sDate: string, eDate: string){
    this.isValidDate = true;
    if((sDate == null || eDate ==null)){
      this.error={isError:true,errorMessage:'Start date and end date are required.'};
      this.isValidDate = false;

    if((sDate != null && eDate !=null) && (eDate) < (sDate)){
      this.error={isError:true,errorMessage:'End date should be grater then start date.'};
      this.isValidDate = false;
    return this.isValidDate;

Componet.HTML :-
<form (ngSubmit)="onSubmit()" #yourForm="ngForm">
  <div class="row form-group">
      <div class="col-sm">
          <label  for="StartDate">Start Date</label>
          <ejs-datepicker format='dd/MM/yyyy' id='datepicker' placeholder='Select start date'
      <div class="col-sm">
              <label  for="EndDate">End Date</label>
              <ejs-datepicker format='dd/MM/yyyy' id='datepicker' placeholder='Select end date'
  <div class="row form-group">
      <div class="col-sm mt-4">                  
          <input type="submit" [disabled]="!yourForm.form.valid" value="Submit" class="btn btn-danger">

Error Display.HTML :-
<div class="text-danger" *ngIf="error.isError">{{error.errorMessage}}</div>

The Result Look like blow pic

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog -
My Books - Book 1 and Book 2 Powered by Blogger.