Thursday, 24 February 2022

Date Validation

 Requirements :

1) All dates before current date are disabled

2) If we select current date, validation message should come (Date should not equal to current date)

3) Date can be valid within the one year from current date.

.ts file code:

todayDate: Date=new Date();

validDate:boolean = false;

validDate2:boolean = false;

enteredDate: string;

nextYearDate: string;


renewDateChange(){

this.enteredDate = moment(event.value).format('YYYY-MM-DD');

    // checking Entered Date is equal to todays date

    if(this.enteredDate === moment(new Date()).format('YYYY-MM-DD')){

      this.validDate2 = true;

    }else {

      this.validDate2 = false;

      // Current date

      const aYearFromNow = new Date();

      // setting validation for 1 year

      aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);

      this.nextYearDate = moment(aYearFromNow).format('YYYY-MM-DD')

      this.validDate = (this.enteredDate <= this.nextYearDate) ? false : true;

    }

}

.html file


<mat-form-field fxFlex="25" class="formField ">

          <mat-label>Program renew by*</mat-label>

          <input matInput [matDatepicker]="picker" [min]="todayDate" formControlName="renewalDate" (dateInput)="renewDateChange($event)" >

          <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>

          <mat-datepicker #picker></mat-datepicker>

          <mat-error *ngIf="f.renewalDate.errors">

            <span *ngIf="f.renewalDate.errors.required">Please provide Renewal Date </span>

          </mat-error>

        </mat-form-field>



PostedBy: pankaj_bhakre

No comments:

Post a Comment