I am currently facing an issue with date validation using moment in TypeScript. Even after providing a range of different date formats and inputting dates according to these formats, the validation always returns false.
HTML
`
<p-calendar [ngModel]="author.birthDate | momentToDateString"
[inline]="false" [required]="true"
name="inpBirthDate" #birthDate="ngModel" [showIcon]="true"
[maxDate]="maxDate" (ngModelChange)="author.birthDate = $event"
[dateFormat]="dateFormat"
(onInput)="author.birthDate = dateTimeUpdate($event)"
[monthNavigator]="appConsts.calendarSettings.monthNavigator"
[yearNavigator]="appConsts.calendarSettings.yearNavigator"
[yearRange]="appConsts.calendarSettings.yearRange">
</p-calendar>
`
TS
`
dateTimeUpdate(event, isTime = false) {
const expectedFormat = isTime ?
this.appConsts.expectedDateTimeFormat :
this.appConsts.expectedDateFormat;
const date = event.target.value;
if (
event !== null && event !== undefined &&
date !== null &&date !== undefined && date !== ''
) {
let formatedDate = moment(date, expectedFormat, true);
if (formatedDate.isValid()) {
return formatedDate.toDate();
}
}
return '';
}
`
expectedDateFormat
`
['dd-MM-YY', 'd-MM-YY']
`
expectedDateTimeFormat
`
['dd-MM-YY, h:mm:ss a', 'd-MM-YY, h:mm:ss a']
`
With the function parameter isTime
set to false, the expectedDateFormat is selected. Despite giving a date like 10-03-21
, it still returns false.