Search code examples
javascripthtmlangulartypescriptangular-reactive-forms

Time Picker validation in angular using default time picker


This is html code basically i want when i open time picker toggle by default is coming current time but I want current time +15 min. onchange method I am validating time and I am trought error also to user. But our requirement is when user click toggle at the time I need show in popup 15min `

<mat-label>Time</mat-label>
<input type="time" matInput [formControl]="TimeFormControl" (change)="timeValidator(15)" >

`

timeValidator(maxTime) {
  const currentDate = new Date();
  const time = this.TimePicker.value.match(/(\d+)(:(\d\d))?\s*(p?)/);
enter const updatedCurrentDate = new Date(currentDate.getTime() + maxTime * 60 * 1000);
  if (time) {
    if (this.selectedDate.setHours(0, 0, 0, 0) === currentDate.setHours(0, 0, 0, 0)) {
      this.selectedDateTime = new Date();
      this.selectedDateTime.setHours(Number(time[1]) + (Number(time[1]) < 12 && time[4] ? 12 : 0));
        this.selectedDateTime.setMinutes(Number(time[3]) || 0);
        if (maxTime) {
          const diff =  (Number(updatedCurrentDate) - Number(this.selectedDateTime)) / (1000 * 60);
          this.checkTime = diff > 1 ? true : false;
        }
        if (!this.checkTime) {
          this.TimePicker.setErrors(null);
        } else {
         this.TimePicker.setErrors({
            incorrect: true,
          });
        }
    } else {
      this.TimePicker.setErrors(null);
    }
  }
} 

Note: I want when i open this toggle button how to set 15min plus current enter image description here


Solution

  • From my understanding you want

    1. You want to validate the time
    • You dont need to validate the time from a timepicker as it will only allow the user to input valid time
    1. when a user clicks on the timepicker its on current time + 15 minutes by default?
    • why not set this as default time when you are building the form?

      TimeFormControl: [new Date(Date.now() + 15 * 60000)]