futerk0
futerk0

Reputation: 1

Disabled Datepicker is validated

I have a form class with several inputs. There is a Checkbox, which enables/disables Datepicker input (Datepicker is not required) based on boolean variable (switchDate). Even if the Datepicker is disabled, it will be still validated and causing whole form to have status invalid. My submit form button condition is: [disabled]="productForm.invalid". Unfortunately this button will be disabled without valid Datepicker field.

My question is: how to validate Datepicker field only if it is enabled?

PS I am newbie to Angular

<input type="checkbox"
             name="switcherChk"
             id="switcherChk" 
             checked="true"
             (change)="changeDatepickerVisibility()" />

  <mat-form-field class="example-full-width">
      <input matInput [matDatepicker]="picker"
                      [min]="todaysDate"
                      placeholder="Example text"
                      formControlName="userDate"
                      [attr.disabled]="switchDate ? '' : null"
                      required = false
                      >
      <mat-datepicker-toggle matSuffix [for]="picker">
        <mat-icon matDatepickerToggleIcon>keyboard_arrow_down</mat-icon>
      </mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
      <mat-error *ngIf="productForm.controls['userDate'].invalid">
          Date should be greater or equal to current date.
        </mat-error>
    </mat-form-field>

Upvotes: 0

Views: 1206

Answers (1)

futerk0
futerk0

Reputation: 1

Resolved this way (on the Component side):

  private changeUserDateValidators(): void{
    var dateControl = this.productForm.get(this.UserDateField);
    if (this.switchDate) {
      dateControl.setValidators(Validators.required);
    }
    else {
      dateControl.clearValidators();
    }
    dateControl.updateValueAndValidity();
}

Depending on what you want to achieve, you can replace Validators.required to your custom validator.

Upvotes: 0

Related Questions