2

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}')])
learning...
  • 3,104
  • 10
  • 58
  • 96

1 Answers1

3

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'),
  ...
});
hgiasac
  • 2,183
  • 16
  • 14
  • Thanks for the validation part. I don't have moment installed, which means i have to `npm install moment --save`. Can't i do without moment? Even though in the patchValue, i have date hardcoded, it is not showing up for me in the control. Why is this? – learning... Aug 18 '18 at 13:41
  • which one to install - recommendations? 1. `https://medium.com/@jek.bao.choo/steps-to-add-moment-js-to-angular-cli-f9ab28e48bf0` 2. `https://www.npmjs.com/package/angular2-moment` – learning... Aug 18 '18 at 13:55
  • just use `npm install --save moment`. Just use it as a library, no need to inject into angular. You can validate without moment.js by using RegExp. However moment has many helpers for Date manipulation. Just use it, DRY – hgiasac Aug 18 '18 at 15:17
  • i am still debating about moment, i don't need it for this project. Hit https://css-tricks.com/prefilling-date-input/ and https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date, This is what is working for me `expDate: new Date('08/08/2018').toISOString().substr(0, 10)` or current as `expDate: new Date(new Date().toLocaleDateString("en-US")).toISOString().substr(0, 10)` or `expDate: '2018-08-08'` the date has to be YYYY-MM-DD. for validation, pattern is working `pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}"` – learning... Aug 19 '18 at 01:10
  • i have created a test bed with your validation and using moment. Here are the thing 1) date only pre-populates as `moment(project.ExpectedDate).format("YYYY-MM-DD")` 2) validation only fires when selecting from calendar 3) when manually entering the date, on submit the value is always empty – learning... Aug 19 '18 at 04:01