Pre-populating and validating date in Angular 6 reactive form

learning... picture learning... · Aug 18, 2018 · Viewed 19.9k times · Source

All the rest of the fields are getting pre-populated except date for me.

For testing purposes, i have hard coded the date as MM/DD/YYYY.

From the DB, i'll get Date and Time, so i'll need to use the pipe to make it MM/DD/YYYY (am i correct about this?)

component code

this.projectForm = new FormGroup({
  'name': new FormControl(project.ProjectName, [Validators.required, Validators.minLength(3), Validators.maxLength(20)]),
  'customerName': new FormControl(project.CustomerName, [Validators.required, Validators.minLength(3), Validators.maxLength(20)]),
  'soNo': new FormControl(project.CustomerOrderId, [Validators.required, Validators.maxLength(30)]),

  'poNo': new FormControl({ value: project.PurchaseOrderId, disabled: true }),

  'expectedDate': new FormControl({ value: project.ExpectedDate, disabled: true }), 
  'installDate': new FormControl(project.InstallDate),
  'closeDate': new FormControl(project.CloseDate),

  'status': new FormControl(project.Status, [Validators.required, ForbiddenProjectStatusValidator.forbiddenProjectStatus])
});


//setting the dates and status dropdown
this.projectForm.patchValue({
  'expectedDate': '08/17/2018',
  'installDate': '08/18/2018',
  'closeDate': '08/19/2018',
  'status': project.Status ? project.Status : "" 
});

html

<input type="date" id="expectedDate" class="form-control" placeholder="Expected Date" formControlName="expectedDate">

Due to input type date, browser shows calendar control.

So basically,

How to

  • pre-populate date
  • validate date that it is MM/dd/yyyy (none of the dates are required). User might not enter or select full date

enter image description here

Update 1:

selected answer is perfect, it details the use of moment but for now i have gone with simplest solution...

https://css-tricks.com/prefilling-date-input/

how to convert current date to YYYY-MM-DD format with angular 2

How to format a JavaScript date

This is what is working for me

expectedDate: new Date('08/08/2018').toISOString().substr(0, 10)

or current as

expectedDate: new Date(new Date().toLocaleDateString("en-US")).toISOString().substr(0, 10) 

or

expectedDate: '2018-08-08' 

the date has to be YYYY-MM-DD.

For validation, pattern is working

'expectedDate': new FormControl(project.InstallDate, [Validators.pattern('[0-9]{4}-[0-9]{2}-[0-9]{2}')])

Answer

hgiasac picture hgiasac · Aug 18, 2018

You can define a custom validator for date. Use date time that support date validation such as moment

import { FormControl } from "@angular/forms";
import * as moment from "moment";

export function DateValidator(format = "MM/dd/YYYY"): any {
  return (control: FormControl): { [key: string]: any } => {
    const val = moment(control.value, format, true);

    if (!val.isValid()) {
      return { invalidDate: true };
    }

    return null;
  };
}

Then use it in form control

{
   ...
  'closeDate': new FormControl(project.CloseDate, [ DateValidator() ]),
}

From the DB, i'll get Date and Time, so i'll need to use the pipe to make it MM/DD/YYYY (am i correct about this?)

You can't use pipe in FormControl. The simplest way is converting to target format before patching value to form

this.projectForm.patchValue({
  'expectedDate': moment(model.expectedDate).format('MM/dd/YYYY'),
  ...
});