eskemaList<T> function
- List<
IValidator> eskema
Returns a Validator that checks a value against the eskema provided, the eskema defines a validator for each item in the list
Example:
final isValidList = eskemaList([isType<String>(), isType<int>()]);
isValidList(["1", 2]).isValid; // true
isValidList(["1", "2"]).isValid; // false
isValidList([1, "2"]).isValid; // false
isValidList
will only be valid:
- if the array is of length 2
- the first item is a string
- and the second item is an int
This validator also checks that the value is a list
Implementation
IValidator eskemaList<T>(List<IValidator> eskema) {
return isType<List>() &
listIsOfLength(eskema.length) &
Validator((value) {
final errors = <Expectation>[];
FutureOr<Result> loop(int index) {
if (index >= value.length) {
return errors.isEmpty
? Result.valid(value)
: Result.invalid(value, expectations: errors);
}
final item = value[index];
final effectiveValidator = eskema[index];
// Nullable short-circuit
if (item == null && effectiveValidator.isNullable) {
return loop(index + 1);
}
final res = effectiveValidator.validator(item);
if (res is Future<Result>) {
return res.then((r) {
_collectListIndex(r, errors, index);
return loop(index + 1);
});
}
_collectListIndex(res, errors, index);
return loop(index + 1);
}
return loop(0);
});
}