i have form and i want to validate date field on submit, i am using Form Builder, how can i do this(the angular way) ? another problem why i cant see the value published_date in the date field ? i tried to search and i can't find solution for input date field.
unamePattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
ngOnInit() {
this.book =
{
id: 55,
author_name : "vv",
published_date : new Date('01/02/2018'),
title : "cc"
};
this.form = this.formBuilder.group({
title : ['', Validators.required],
author : ['', Validators.required],
datePublish: ['', Validators.pattern(this.unamePattern)],
}
);
}
<input
[(ngModel)]="book.published_date"
id="dateOfBirth"
class="form-control"
placeholder="yyyy-mm-dd"
name="dp"
ngbDatepicker
formControlName="datePublish"
#dp="ngbDatepicker">
<div class="input-group-append">
<button class="btn btn-outline-secondary" (click)="dp.toggle()" type="button">
<i class="fa fa-calendar" aria-hidden="true"></i>
</button>
</div>
If you could use momemt()
then it will very easy to get hands on date time things and you could write your own validator as
import {AbstractControl} from '@angular/forms';
import * as moment from 'moment';
export class YourValidator {
static dateVaidator(AC: AbstractControl) {
if (AC && AC.value && !moment(AC.value, 'YYYY-MM-DD',true).isValid()) {
return {'dateVaidator': true};
}
return null;
}
}
And in your form object you could use it like
import {YourValidator} from "....";
this.form = this.formBuilder.group({
title : ['', Validators.required],
author : ['', Validators.required],
datePublish: ['', Validators.compose([Validators.required, YourValidator.dateVaidator])],
});
Demo stackblitz.com/angular-date-validator
For date validation you can use ng4-validators.
npm i ng4-validators --save
Import and use:
import { CustomValidators } from 'ng4-validators';
ngOnInit() {
this.book =
{
id: 55,
author_name : "vv",
published_date : new Date('01/02/2018'),
title : "cc"
};
this.form = this.formBuilder.group({
title : ['', Validators.required],
author : ['', Validators.required],
datePublish: ['', CustomValidators.date,
}
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With