toBoolLenient function

IValidator toBoolLenient(
  1. IValidator child, {
  2. String? message,
})

Lenient / permissive bool coercion.

Accepts booleans, ints 1/0, and these case-insensitive string forms:

  • true / false
  • t / f
  • yes / no
  • y / n
  • on / off
  • 1 / 0

Use this when you need to ingest loosely formatted user input. Prefer toBool or toBoolStrict for stricter validation where accidental typos should fail fast.

See also:

Implementation

IValidator toBoolLenient(IValidator child, {String? message}) {
  const trueSet = {'true', 't', 'yes', 'y', 'on', '1'};
  const falseSet = {'false', 'f', 'no', 'n', 'off', '0'};
  final $stringBoolMatcher = ($isBool |
      isOneOf([0, 1]) |
      toLowerCase(
        isString() &
            isOneOf(['true', 'false', 't', 'f', 'yes', 'no', 'y', 'n', 'on', 'off', '1', '0']),
      ));
  final transformToBool = core.transform(
    (v) {
      return switch (v) {
        final bool b => b,
        final int i => i == 1,
        final String s => () {
            final lower = s.toLowerCase().trim();
            if (trueSet.contains(lower)) return true;
            if (falseSet.contains(lower)) return false;
            return null;
          }(),
        _ => null,
      };
    },
    child,
  );

  final validator = $stringBoolMatcher & transformToBool;

  return handleReturnPreserveValue(validator, message);
}