Kees de Bruin
Kees de Bruin

Reputation: 551

Bug in mat-datepicker when entering invalid input

I have the following code for a simple material datepicker:

<mat-form-field class="mat-form-field--block" floatLabel="always">
  <mat-label
    translate="DATE_OF_BIRTH"
  ></mat-label>
  <input
    matInput
    [matDatepicker]="dateOfBirth"
    [formControlName]="date_of_birth.name"
    placeholder="dd-mm-jjjj"
  />
  <mat-datepicker-toggle matSuffix [for]="dateOfBirth">
    <mat-icon
      matDatepickerToggleIcon
      fontSet="far"
      fontIcon="fa-calendar-day"
    ></mat-icon>
  </mat-datepicker-toggle>
  <mat-datepicker #dateOfBirth></mat-datepicker>
</mat-form-field>

The form is build using:

public form = this.fb.group({
  [this.date_of_bith.name]: [null, Validators.required],
});

public date_of_birth(): AbstractControl {
  return this.form.get(this.date_of_birth.name);
}

We are using the Luxon date adapter with no special options or formats set. The adapter is imported as:

import { MatLuxonDateModule } from '@angular/material-luxon-adapter';

Now the problem is when I enter e.g. 23 in the input and press the tab-key, the date is changed to today's date. How can I prevent this from happening?

Update: after searching some more it seems that the Luxon adapter first tries to parse the string as an ISO date. How can I disable this and only use the specified format?

Upvotes: 0

Views: 1161

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

By default parsing is done in a forgiving way. You should enable strict mode to see the date converted only when the date is entered accurately.

@NgModule({
  imports: [
    MatDatepickerModule,
    MatMomentDateModule,
    ...
  ],
  providers: [
    {
      provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS,
      useValue: {strict: true} // <-- enable strict mode like this
    }
  ]
})

Stackblitz

Upvotes: 1

Related Questions