0

Using the Angular Materials datepicker. When I choose a date from the datepicker, the field shows up red as invalid.

Heres's the template:

<form [formGroup] = "addEvent"  (ngSubmit)="onSubmit()">
   <mat-form-field>
    <input matInput formControlName = "eventDate" [matDatepicker] = "eventDate" placeholder = "Choose a date">
   <mat-datepicker-toggle matSuffix [for] = "eventDate"></mat-datepicker-toggle>
   <mat-datepicker #eventDate></mat-datepicker>
  </mat-form-field>
 </form>

Here's the Reactive forms code. The regex is tested and works with or without leading zeroes.

  addEvent = this.formBuilder.group({
    eventDate: ['', Validators.pattern('[0-9]?[0-9]{1}\/[0-9]?[0-9]+\/[0-9]{4}')]
  });
MaxRocket
  • 920
  • 1
  • 12
  • 26
  • 1
    from https://stackoverflow.com/questions/53333497/angular-material-datepicker-with-input-validation , I quote... It happens because matDatepicker binds a Date object, not a simple string as "AAA-MM-DD"... – Akber Iqbal Jun 10 '19 at 11:51
  • So, @AkberIqbal, I assume I'd have to create a custom validator, there's no easy shortcut? Also, I'm unsure how to do that here, can you help? Thanks – MaxRocket Jun 10 '19 at 11:59
  • You can assign the target value from mat-datapicker into a separate formcontrol variable and do a validation on it... but that would be a workaround (not a clean way)... – Akber Iqbal Jun 10 '19 at 12:01
  • @AkberIqbal what's the clean way? – MaxRocket Jun 10 '19 at 12:05
  • 1
    custom validation – Akber Iqbal Jun 10 '19 at 12:21
  • @AkberIqbal I can't figure out where in app.module.ts to put a custom validator. The documentation is shoddy af – MaxRocket Jun 10 '19 at 12:25

1 Answers1

1

just create a ValidatorFn and add it to the Validators arrays of FormControl. here is a simple demo;

https://stackblitz.com/edit/angular-1egypt

ysf
  • 4,634
  • 3
  • 27
  • 29