maxDecimals function
max_decimals: the number must have at most the given number of digits
after the decimal point: {max_decimals: 2}. Trailing zeros do not
count, so '1.230' and 1.230 have 2. Strings are accepted in the form
-12 or -12.34, and the output is the number.
Implementation
LivrRule maxDecimals(List<Object?> args, RuleContext context) {
// Arguments after the first one are ignored. A string in the grammar of
// decimal is the number: '2', '2.0', '02', not ' 2' or '1e1'
final arg = args.isEmpty ? null : args[0];
final number = arg is num
? arg
: (arg is String && arg.isNotEmpty && _countDecimals(arg) >= 0
? parseNumber(arg)
: null);
if (number == null || number < 0 || number != number.truncateToDouble()) {
throw LivrSchemaException(
'Rule [max_decimals] expects a non-negative integer, got [$arg]',
);
}
final maxDecimals = number.toInt();
return (value, allValues) {
if (value is String) {
if (value.isEmpty) return RuleResult.valid;
final decimals = _countDecimals(value);
if (decimals < 0) return RuleResult.error('NOT_NUMBER');
// Too large for a finite double: not a number, as JSON has no
// infinity. Checked before the decimals: a bound code means a number
final number = parseNumber(value);
if (number == null) return RuleResult.error('NOT_NUMBER');
if (decimals > maxDecimals) return RuleResult.error('TOO_MANY_DECIMALS');
return RuleResult.value(number);
}
if (value is int) return RuleResult.valid;
if (value is double) {
if (!value.isFinite) return RuleResult.error('FORMAT_ERROR');
return _countNumberDecimals(value) > maxDecimals
? RuleResult.error('TOO_MANY_DECIMALS')
: RuleResult.valid;
}
if (value == null) return RuleResult.valid;
return RuleResult.error(value is bool ? 'NOT_NUMBER' : 'FORMAT_ERROR');
};
}