switchBy function

IValidator switchBy(
  1. String key,
  2. Map<String, IValidator> by
)

Creates a polymorphic (switch-case) validator that depends on the value of a key in the parent map.

Usage Examples:

final schema = switchBy('type', {
  'business': eskema({
    'taxId': required(isString()) & stringLength([isGte(5)]),
  }),
  'person': eskema({
    'name': required(isString() & stringLength([isGte(5)])),
  }),
});
final result = schema.validate({'type': 'business', 'taxId': '123456789'});
print(result);

Implementation

IValidator switchBy(String key, Map<String, IValidator> by) {
  return $isMap &
      containsKeys([key], message: 'Missing key: "$key"') &
      Validator((value) {
        final type = value[key];
        final v = by[type];
        final r = v?.validate(value);

        if (r == null) {
          return Result.invalid(
            value,
            expectation: const Expectation(message: 'unknown type'),
          );
        }

        return r.isValid ? Result.valid(value) : r;
      });
}