Skip to content

l.union()

Tries each option in order against the same value and returns the output of the first that passes. When none passes, it reports one invalidUnion issue whose params['issues'] holds every option’s issues. Returns a UnionValidator<Object?>; the output type is Object? because the options may differ. Use it for list elements of mixed shape, l.list(l.union([...])), or for a field that may be an id or an email.

UnionValidator<Object?> union(List<ValidatorReference<Object?>> options, {String? message, MessageBuilder? messageBuilder})
Parameter Type Meaning
options List<ValidatorReference<Object?>> Tried in order. Must not be empty; an empty list throws ArgumentError when the validator is built.
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 invalidUnion. Default message: value does not match any allowed option. value is replaced by the field name when there is one.

The generator does not emit unions yet. freezed union classes fail generation with an error that names the class.

final idOrEmail = l.union([l.int().min(1), l.string().email()]);
idOrEmail.validate(input)+3-2
  1. valid: 42
  2. valid: '[email protected]'
  3. invalid: 'bad'value does not match any allowed option
  4. invalid: 0value does not match any allowed option
  5. valid: null

The single issue carries each option’s issues, so a UI can explain why nothing matched:

invalidUnion
[ValidationIssue(code: invalidType, path: , message: value must be an integer)]
[ValidationIssue(code: invalidEmail, path: , message: value must be a valid email address)]