withExpectation function
- IValidator child,
- Expectation error, {
- String? message,
Returns a IValidator that wraps the given child validator and adds the
provided error message to the result if the validation fails.
Preserves the underlying child's code and data (if the child failed).
See docs/expectation_codes.md.
Usage Examples:
// Custom error message for age validation
final ageValidator = withExpectation(
isInRange(0, 150),
Expectation(message: "Age must be between 0 and 150 years")
);
// Localized error messages
final nameValidator = withExpectation(
stringLength([isGte(2)]),
Expectation(message: "El nombre debe tener al menos 2 caracteres")
);
// Preserve error codes while customizing message
final emailValidator = withExpectation(
$isEmail,
Expectation(message: "Please enter a valid email address", code: "email.invalid")
);
Implementation
IValidator withExpectation(IValidator child, Expectation error, {String? message}) =>
Validator<Result>((value) {
final result = child.validator(value);
Expectation build(Result r) => _applyOverride(
error,
message,
value,
code: r.isValid ? null : r.firstExpectation.code,
);
if (result is Future<Result>) {
return result.then(
(r) => Result(isValid: r.isValid, expectation: build(r), value: value),
);
}
return Result(isValid: result.isValid, expectation: build(result), value: value);
});