Thursday, November 21, 2019

Angular 7 and 8 Validate Two Dates

Angular 7 and 8 Validate Two Dates

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”.
Angular 7 and 8 Validate Two Dates

Let’s see the example
import { Component, OnInit } from '@angular/core';
import { UserRequest } from '../model/user';
@Component({
  selector: 'User_Cal',
  templateUrl: './usercal.component.html',
  styleUrls: ['./usercal.component.css']
})
export class UserCalComponent implements OnInit {
  constructor(private EncrDecr: EncrDecrService, private  http:  HttpClient,
              private datePipe: DatePipe) {           
              }
  //model class
  model = new UserRequest(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.EndDate = this.datePipe.transform(this.model.EndDate,"dd-MM-yyyy"); 
    this.isValidDate = this.validateDates(this.model.StartDate, this.model.EndDate);
    if(this.isValidDate){
       this.http.post<UserRequest>(environment.API_URL + "User/StEtDate", this.model, this.options)
          .subscribe(res => {
              console.log(res);
            },
            err => {
              console.log(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'
              [(value)]='model.StartDate'></ejs-datepicker>                       
      </div>
      <div class="col-sm">
              <label  for="EndDate">End Date</label>
              <ejs-datepicker format='dd/MM/yyyy' id='datepicker' placeholder='Select end date'
                  [(value)]='model.EndDate'></ejs-datepicker>
      </div>
  </div>
  <div class="row form-group">
      <div class="col-sm mt-4">                 
          <input type="submit" [disabled]="!yourForm.form.valid" value="Submit" class="btn btn-danger">
      </div>
  </div>
</form>
Error Display.HTML
<div class="text-danger" *ngIf="error.isError">{{error.errorMessage}}</div>

No comments:

Post a Comment