Skip to content

l.map()

Passes when the value is a Map and, if given, every key passes keyValidator and every value passes valueValidator. Without validators, keys and values are only checked to be of type K and V. A value failure is reported at the key’s path, such as scores.alice. A key failure is one invalidKey issue at the map’s own path, so key and value errors never share a path. The output is a new Map<K, V> of the valid entries. Use l.schema() when the keys are known field names.

MapValidator<K, V, Map<K, V>?> map<K, V>({ValidatorReference<K>? keyValidator, ValidatorReference<V>? valueValidator, String? message, MessageBuilder? messageBuilder})
Parameter Type Meaning
keyValidator ValidatorReference<K>? Runs on every key.
valueValidator ValidatorReference<V>? Runs on every value.
message String? Replaces the default error message.
messageBuilder MessageBuilder? Builds the message from the issue. message wins when both are given. See Message builders.

Code invalidType. Default message: value must be a map when the value is not a map. A failing key produces value has an invalid key "k" with code invalidKey, params['key'] and params['issues']. Values carry their own validator’s code. value is replaced by the field name when there is one.

A Map<K, V> parameter maps to l.map(keyValidator:, valueValidator:) with validators derived from K and V. JSON object keys are strings, so a key type of int, double, num or BigInt becomes l.string().custom(...) that parses the string, and an enum key becomes l.oneOf() of the serialized names.

final scores = l.map(
keyValidator: l.string().email().required(),
valueValidator: l.int().required(),
);
scores.validate(input)+1-2
  1. valid: {'[email protected]': 10}
  2. invalid: {'not-an-email': 'x'}value has an invalid key "not-an-email"not-an-email: value must be an integer
  3. invalid: []value must be a map

The error map for the failing input, with the key error at the map’s path and the value error at the key’s path:

{: [value has an invalid key "not-an-email"], not-an-email: [value must be an integer]}

Without validators, only the type arguments are checked:

ValidationSuccess(data: {a: 1})
{a: [value must be an int]}