1

I have a program that takes a Date from user input in format dd.mm.yyyy .

However, when a wrong Date is entered, such as 30.02.2020, The days overflow and set the months to 3. I'd rather be able to tell the user that that date isn't possible. Is there a way to do this in js?

A Dude
  • 27
  • 4
  • 1
    There are many questions with good answers on [how to validate a date](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+validate+a+date). – RobG Mar 19 '20 at 20:16

1 Answers1

3

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
    }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I can't believe I didn't think of this. Thanks, you'll get your checkmark in a few mins! :) – A Dude Mar 19 '20 at 14:23
  • Surely you only need to check if the month is different due to overflow? If the day or year are different, the month will be too? – Ben Aston Mar 19 '20 at 14:30
  • 1
    @52d6c6af - Only if you restrict days to two digits. :-) (Consider `new Date(2020, 2, 365)`) I tend toward defensive programming... – T.J. Crowder Mar 19 '20 at 14:52