Angular 7 Start Date End Date Validation

Angular 7 Validate two dates - Start Date & End Date

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

Here, I’m validating to “Next pay date should be grater then start date”.

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

@Component({
  selector: 'APRCalculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {
  constructor(private EncrDecr: EncrDecrService,
              private  http:  HttpClient,
              private datePipe: DatePipe)
              {   }

  //model class
  model = new LoanRequest(null, null, null, null, null);

  //Error Display
  error:any={isError:false,errorMessage:''};
  isValidDate:any;

  ngOnInit() {
  }

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

    this.isValidDate = this.validateDates(this.model.StartDate, this.model.NextPayDate);
    if(this.isValidDate){
       this.http.post<LoanRequest>(environment.API_URL + "Calculate/APR", this.model, this.options)
          .subscribe(res => {
              console.log(res);

              //func - clear UI
              this.clearAPRCAL();
            },
            err => {
              console.log(err);
          });
    } 
  }

  validateDates(sDate: string, npDate: string){
    this.isValidDate = true;

    if((sDate == null || npDate ==null)){
      this.error={isError:true,errorMessage:'The StartDate and Next PayDate are Required. '};
      this.isValidDate = false;
    }

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

    return this.isValidDate;
  }
 }


Componet.HTML
<form (ngSubmit)="onSubmit()" #loanForm="ngForm">
            <div class="row form-group">
                <div class="col-sm">
                        <label for="">Loan Amount</label>
                        <input type="text" numbersOnly required  [(ngModel)]="model.LoanAmount" id="LoanAmount" name="LoanAmount" class="form-control" placeholder="Loan amount">
                </div>
                <div class="col-sm">
                        <label for="">Loan tenure</label>
                        <input type="text" numbersOnly required [(ngModel)]="model.LoanTenure" id="LoanTenure" name="LoanTenure" class="form-control" placeholder="Loan tenure">
                </div>
            </div>
            <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'
                        [(value)]='model.StartDate'></ejs-datepicker>                         
                </div>
                <div class="col-sm">
                        <label  for="StartDate">Next Pay Date</label>
                        <ejs-datepicker format='dd/MM/yyyy' id='datepicker' placeholder='Select next pay date'
                            [(value)]='model.NextPayDate'></ejs-datepicker>
                </div>
            </div>
            <div class="row form-group">
                <div class="col-sm">     
                    <label for="">Interest Rate</label>
                    <input type="text" OnlyNumeric required [(ngModel)]="model.InterestRate" id="InterestRate" name="InterestRate" class="form-control" placeholder="Interest rate">          
                </div>
                <div class="col-sm mt-4">                   
                    <input type="submit" [disabled]="!loanForm.form.valid" value="Submit" class="btn btn-danger btnRed">
                </div>
            </div>
        </form>

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


Result Looks like –
ANIL SINGH

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 Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^