toothful
toothful

Reputation: 892

Angular material date picker: check invalid date for not required date field

Angular material date picker returns moment object and it returns null for both invalid date format as well as null/empty date field.

Is there any way to distinguish between invalid date format and empty date.

Upvotes: 2

Views: 5352

Answers (2)

Gauthier Peel
Gauthier Peel

Reputation: 1518

In Angular Material 8, there is formatting error distinct from the required error which only appears if you had the Validators.required validators.

With a wrong date format you get the following errors :

birthdate.errors = {
  "required": true,
  "matDatepickerParse": {
    "text": "44/3/2020"
  }
}

So to distinguish look at the error under "matDatepickerParse" key.

With an empty input you get :

birthdate.errors = {
  "required": true
}

Upvotes: 2

wentjun
wentjun

Reputation: 42596

If you are using Angular's Reactive Forms, you can include Validator methods on the Form Controls, such that they will be flagged with the respective errors.

yourForm = this.formBuilder.group({
  date: [null, Validators.required]
});

You can access the errors on the above Abstract Control by calling the errors property, as specified on the documentation.

this.yourForm.controls.date.valid;
// returns true or false

If you want to check for a specific error, such as required, you may make use of the hasError() method

this.yourForm.controls.date.hasError('required');

Upvotes: 2

Related Questions