isIso8601 function

bool isIso8601(
  1. String str
)

Returns true if str is a full ISO 8601 date or date-time.

Stricter than isDate in two ways: the space-separated form 2024-06-15 10:00:00 that DateTime.tryParse tolerates is rejected, and so is an out-of-range component. DateTime.tryParse silently rolls those over — 2024-13-01 becomes January 2025 and 2023-02-29 becomes March — whereas this returns false.

Implementation

bool isIso8601(String str) {
  final trimmed = str.trim();
  final match = _iso8601Reg.firstMatch(trimmed);
  if (match == null) return false;
  if (DateTime.tryParse(trimmed) == null) return false;

  // Reject rolled-over dates by checking the calendar day survives a
  // round-trip through DateTime.utc.
  final year = int.parse(match.group(1)!);
  final month = int.parse(match.group(2)!);
  final day = int.parse(match.group(3)!);
  final probe = DateTime.utc(year, month, day);
  return probe.year == year && probe.month == month && probe.day == day;
}