check method
Applies an additional validation rule to this result.
Behavior depends on the current state:
- If Invalid: Adds
errorto the existing error set and returns Invalid - If Valid: Evaluates
ruleon the value:
Errors accumulate in a Set, so calling check multiple times with the same
error won't create duplicates. The original value is preserved through
the entire chain.
Parameters:
rule: Predicate function that returns true if valid, false if invaliderror: Error message to include if this validation fails
Example:
// Successful chain - all rules pass
final result = Valid('Alice')
.check((n) => n.length >= 2, 'Too short')
.check((n) => n.length <= 20, 'Too long');
// result is Valid('Alice')
// Failed chain - collects all errors
final result2 = Valid('A')
.check((n) => n.length >= 2, 'Too short')
.check((n) => n.length <= 1, 'Must be max 1 char');
// result2 is Invalid({'Too short'})
// Chaining on Invalid - errors keep accumulating
final result3 = Invalid<String>({'Required'}).check(
(_) => false,
'Too short',
);
// result3 is Invalid({'Required', 'Too short'})
Implementation
Validated<T> check(bool Function(T) rule, {required String error}) =>
switch (this) {
Invalid(:final errors) => .invalid({...errors, error}),
Valid(:final value) => rule(value) ? this : .invalid({error}),
};