There isn't any way to make the Date
object do this, no. You have to handle it outside the Date
object.
One fairly simple way is to check the fields after construction:
const parts = /^(\d+)\.(\d+)\.(\d+)$/;
if (parts) {
const day = +parts[1];
const month = +parts[2] - 1;
const year = +parts[3];
const dt = new Date(year, month, day);
if (dt.getFullYear() !== year || dt.getMonth() !== month || dt.g etDate() !== day) {
// overflow
}
}
Or in a really up-to-date environment with named capture groups:
const parts = /^(?<day>\d+)\.(?<month>\d+)\.(?<year>\d+)$/;
if (parts) {
const day = +parts.groups.day;
const month = +parts.groups.month - 1;
const year = +parts.groups.year;
const dt = new Date(year, month, day);
if (dt.getFullYear() !== year || dt.getMonth() !== month || dt.g etDate() !== day) {
// overflow
}
}