'angular 6 reactive form and input type date format

In my angular 6 application, I am developing a reactive contact form, wherein I have a date field in which the user can enter the date of birth, in the .html file I have the below code.

<input type="date" formControlName="dob"/>

and in .ts file I have code as:

this.contactForm= this.fb.group({
 dob:[''],
})

Now the issue is that when the user is selecting a date the format of the data is given as per his/her system, however, I want to set it up as MM/DD/YYYY format and so I added a placeholder in the date input as below <input type="date" placeholder="MM/DD/YYYY"> but this does not work as well.

Can anyone please help me how to set up the date format system independently?



Solution 1:[1]

VALIDATING

So when you are creating the FormGroup, you can pass in validation methods and or constraints there are several of them see this.

I am assuming you want to validate the user input when the form is submitted.

 postalCode: [
    address?.postalCode,
    [
      Validators.pattern("YOUR REGEX"),
      Validators.required
    ]
  ],

In this example i am creating the child group postalCode, which consists of the default value from property postalCode on the address object (if it isn't null).

Then as the second parameter, i am passing in a array of validation options, the first one is a REGEX pattern validation constraint which takes a string value as pattern. From there on you can implement a regex pattern which works for your desired date formats.

there are also other predefined validation methods see this. https://angular.io/api/forms/Validators

also this if you want to render validation erros messages etc. https://angular.io/guide/form-validation

i hope that helps don't be afraid to ask if you encounter issues.

CONVERTING

You can also convert dates submitted from the form using the built in formatDate function

import format date

import { formatDate } from '@angular/common';

formatDate(DateToBeFormated, Format, LOCALE (EN / DE) or something)

this.form = this.formBuilder.group({
  date: [formatDate(date, 'yyyy-MM-dd', 'en' [Validators.required]],});

for example

for additional help see this post How can I set my reactive form date input value?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1