Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isISODate

Checks if a string is a valid ISO 8601 date string.

TypeScript
Copied!
1/**
2 * Checks if a string is a valid ISO 8601 date string.
3 *
4 * Accepts formats like:
5 * - "2023-06-30"
6 * - "2023-06-30T15:20:30Z"
7 * - "2023-06-30T15:20:30+02:00"
8 *
9 * @param str - The date string to validate.
10 * @returns True if the string is a valid ISO date.
11 */
12export function isISODate(str: string): boolean {
13  const isoRegex = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[\+\-]\d{2}:\d{2})?)?$/;
14  return isoRegex.test(str) && !isNaN(Date.parse(str));
15}
  • Strict ISO 8601 Compliance

    The regex explicitly enforces ISO 8601 formats, supporting both date-only and full datetime variants with optional timezone info.

  • Dual-Layer Validation

    Combines regex format checking with Date.parse to ensure both syntactic and semantic correctness.

  • Supports Timezone Offsets and UTC

    Accepts both Z (UTC) and ±HH:MM offsets, covering the full range of ISO-compatible datetime strings.

  • Efficient and Lightweight

    Validation is done with minimal computation, making it suitable for large-scale input checks.

Tests | Examples

TypeScript
Copied!
1test('isISODate - accepts ISO date only', () => {
2  expect(isISODate('2023-06-30')).toBe(true);
3});
4
5test('isISODate - accepts full ISO datetime with Z', () => {
6  expect(isISODate('2023-06-30T15:20:30Z')).toBe(true);
7});
8
9test('isISODate - accepts ISO datetime with timezone offset', () => {
10  expect(isISODate('2023-06-30T15:20:30+02:00')).toBe(true);
11});
12
13test('isISODate - rejects malformed date', () => {
14  expect(isISODate('2023/06/30')).toBe(false);
15});
16
17test('isISODate - rejects invalid date', () => {
18  expect(isISODate('2023-02-30')).toBe(false);
19});
20
21test('isISODate - rejects random text', () => {
22  expect(isISODate('not-a-date')).toBe(false);
23});

Common Use Cases

  • API Payload Validation

    Ensure incoming date strings from JSON APIs conform to ISO standards before parsing or storing.

  • Form Input Validation

    Validate date/time fields in user-facing forms (e.g., booking systems, schedulers).

  • Data Import/Export

    Sanitize or validate date strings when transferring data between systems or formats.

  • Database Timestamp Checks

    Confirm that dates stored or retrieved from a database follow the expected ISO format.

Codebase: Utilities -> Validation -> isISODate | Yevhen Klymentiev