check method

Validated<T> check(
  1. bool rule(
    1. T
    ), {
  2. required String error,
})

Applies an additional validation rule to this result.

Behavior depends on the current state:

  • If Invalid: Adds error to the existing error set and returns Invalid
  • If Valid: Evaluates rule on the value:
    • If rule returns true: Returns this Valid unchanged
    • If rule returns false: Returns Invalid with the error

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 invalid
  • error: 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}),
    };