CodingNic

API, Persistence, and Hardening

Validate Real Calendar Dates

API, Persistence, and Hardening 16 min read

Validate Real Calendar Dates

A text field can give you a string with the correct shape but still contain an impossible date. 2026-02-31 matches YYYY-MM-DD, but it is not a real calendar date.

Open client/src/lib/finance.js and use a helper that checks both the format and the calendar components:

javascript
export function isValidDateOnly(value) {
  if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;

  const [year, month, day] = value.split("-").map(Number);
  const date = new Date(Date.UTC(year, month - 1, day));

  return (
    date.getUTCFullYear() === year &&
    date.getUTCMonth() === month - 1 &&
    date.getUTCDate() === day
  );
}

There are two details worth understanding before you copy this:

First, JavaScript months are zero-based. January is 0, February is 1, and so on. That is why the code compares month - 1 with the UTC month.

Second, the helper uses UTC only to perform a calendar check. We are not saying the transaction happened in a UTC timezone; we are using a timezone-independent date representation so a date such as 2026-09-17 remains the same calendar date during validation.

Use the same rule in server/src/domain/transactions.js and reject the request before the transaction reaches db.transactions.

Test it

Check these values:

text
2026-02-28  → valid
2026-02-29  → invalid in 2026
2024-02-29  → valid in a leap year
2026-99-99  → invalid

Also submit an invalid date directly to the API if you are using a tool such as the browser network panel or another HTTP client. The server should reject it even when the React form is bypassed.

Checkpoint

The date rule now protects both sides of the application: the browser can give immediate feedback, and the server prevents invalid calendar dates from being persisted.