isoTime function
iso_time: the value must be a time of day without an offset, HH:MM,
HH:MM:SS or HH:MM:SS.fraction with 1-9 digits, as
<input type="time"> sends it. The value is not changed.
With bounds, {iso_time: {'min': '09:00', 'max': '18:00'}}, the time must
be in the range, both bounds included. With min after max the range
goes over midnight: {'min': '22:00', 'max': '06:00'} accepts 23:30 and
05:59, and a time between them gets the error of the nearer bound.
Implementation
LivrRule isoTime(List<Object?> args, RuleContext context) {
if (args.isEmpty) return _isoTime;
// Arguments after the options are ignored
final options = args[0];
if (options is! Map<Object?, Object?>) {
throw LivrSchemaException(
'Rule [iso_time] 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_time] got an unknown option [$key]');
}
}
final min = options.containsKey('min')
? _parseBound(options['min'], 'min')
: null;
final max = options.containsKey('max')
? _parseBound(options['max'], 'max')
: null;
if (min == null && max == null) return _isoTime;
if (min == null || max == null || min <= max) {
final minTime = min ?? 0;
final maxTime = max ?? _dayNs;
return (value, allValues) {
if (value is! String) return _notString(value);
if (value.isEmpty) return RuleResult.valid;
final time = _parseTime(value);
if (time < 0) return RuleResult.error('WRONG_TIME');
if (time < minTime) return RuleResult.error('TIME_TOO_EARLY');
if (time > maxTime) return RuleResult.error('TIME_TOO_LATE');
return RuleResult.valid;
};
}
// Over midnight: a time in the gap between max and min gets the error of
// the nearer bound, TIME_TOO_EARLY exactly in the middle
return (value, allValues) {
if (value is! String) return _notString(value);
if (value.isEmpty) return RuleResult.valid;
final time = _parseTime(value);
if (time < 0) return RuleResult.error('WRONG_TIME');
if (time >= min || time <= max) return RuleResult.valid;
return RuleResult.error(
time - max < min - time ? 'TIME_TOO_LATE' : 'TIME_TOO_EARLY',
);
};
}