toBool function

IValidator toBool(
  1. IValidator child
)

Coerces a value to a boolean.

Handles existing booleans, the integers 1 and 0, and the strings "true" and "false". The check is case-insensitive. Passes the resulting boolean to the child validator.

Implementation

IValidator toBool(IValidator child) {
  return ($isBool | isOneOf([0, 1]) | (toLowerCase(isString() & isOneOf(['true', 'false'])))) &
      transform((v) {
        return switch (v) {
          final bool b => b,
          final int i => i == 1,
          final String s => s.toLowerCase().trim() == 'true',
          _ => null,
        };
      }, child);
}