withExpectation function

IValidator withExpectation(
  1. IValidator child,
  2. Expectation error
)

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.

Implementation

IValidator withExpectation(IValidator child, Expectation error) => Validator<Result>((value) {
      final resOr = child.validator(value);

      if (resOr is Future<Result>) {
        return resOr.then((r) => Result(
              isValid: r.isValid,
              expectations: [
                error.copyWith(value: value, code: r.isValid ? null : r.firstExpectation.code)
              ],
              value: value,
            ));
      }

      return Result(
        isValid: resOr.isValid,
        expectations: [
          error.copyWith(value: value, code: resOr.isValid ? null : resOr.firstExpectation.code)
        ],
        value: value,
      );
    });