isoDatetime function
iso_datetime: the value must be a date and a time with an offset,
YYYY-MM-DDTHH:MM[:SS[.fraction]] and Z or +HH:MM/-HH:MM. The
output is the instant in UTC with three fraction digits, cut off, not
rounded: '2026-10-29T10:00:00.123456+02:00' becomes
'2026-10-29T08:00:00.123Z'.
With bounds, {iso_datetime: {'min': '2026-01-01T09:00:00Z', 'max': 'tomorrow'}}, the instant must be in the range, both bounds included. A
bound is a datetime, a date (the start of the UTC day as min, its end
as max), or 'today', 'yesterday' or 'tomorrow', the UTC days of
the clock of the validator. Arguments after the options are ignored.
Implementation
LivrRule isoDatetime(List<Object?> args, RuleContext context) {
if (args.isEmpty) return _isoDatetime;
final options = args[0];
if (options is! Map<Object?, Object?>) {
throw LivrSchemaException(
'Rule [iso_datetime] expects no arguments or an object with "min" and '
'"max", got [$options]',
);
}
for (final key in options.keys) {
if (key != 'min' && key != 'max') {
throw LivrSchemaException(
'Rule [iso_datetime] got an unknown option [$key]',
);
}
}
// A fixed bound is the key of an instant (see _key), a relative one is the
// number of days from the current date
final min = options.containsKey('min')
? _parseBound(options['min'], isMax: false)
: null;
final max = options.containsKey('max')
? _parseBound(options['max'], isMax: true)
: null;
if (min == null && max == null) return _isoDatetime;
final minKey = min?.key ?? -_maxKey;
final maxKey = max?.key ?? _maxKey;
final minDays = min?.days;
final maxDays = max?.days;
// No value could pass. The keys are cut to milliseconds. A fixed and a
// relative bound are not compared: the result depends on the day, and
// that can be intended
if (min != null &&
max != null &&
(minDays == null
? maxDays == null && minKey > maxKey
: maxDays != null && minDays > maxDays)) {
throw LivrSchemaException(
'Rule [iso_datetime] got min [${options['min']}] later than max '
'[${options['max']}]',
);
}
final clock = minDays != null || maxDays != null ? context.clock : null;
return (value, allValues) {
if (value is! String) return _notString(value);
if (value.isEmpty) return RuleResult.valid;
final form = _parse(value);
if (form < 0 || _utcYear < 0 || _utcYear > 9999) {
return RuleResult.error('WRONG_DATETIME');
}
final key = _key();
if (clock == null) {
if (key < minKey) return RuleResult.error('DATETIME_TOO_EARLY');
if (key > maxKey) return RuleResult.error('DATETIME_TOO_LATE');
} else {
// One clock read per value: the current date in UTC, never in the
// local time zone
final today = _dayNumber(clock());
final minBound = minDays == null ? minKey : _relativeKey(today, minDays);
if (key < minBound) return RuleResult.error('DATETIME_TOO_EARLY');
final maxBound = maxDays == null
? maxKey
: _relativeKey(today, maxDays) + _dayMs - 1;
if (key > maxBound) return RuleResult.error('DATETIME_TOO_LATE');
}
return form == _outputForm ? RuleResult.valid : RuleResult.value(_format());
};
}