Skip to content

l.schema()

Passes when the value is a map and every declared field passes its validator. A missing field is skipped unless its validator is required. Unknown keys are stripped from the output by default; .passthrough() keeps them and .strict() rejects them. The output is a new Map<String, Object?> with the validated value of each present field. Validate with validate, or with validateSchema to convert the output with fromJson. Schemas explains nesting, reuse and forward references.

SchemaValidator<Map<String, Object?>?> schema(Map<String, ValidatorReference<Object?>> fields, {String? message, MessageBuilder? messageBuilder})
ValidationResult<T> validateSchema<T>(Object? input, {required FromJson<T> fromJson})
Parameter Type Meaning
fields Map<String, ValidatorReference<Object?>> Field name to validator. Values may be validators, nested schemas, or forward references.
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; message and messageBuilder apply to that case only. Field failures carry their own code at the field’s path and use the field key as the field name. A fromJson that throws produces value could not be converted with code fromJsonFailed, and null input to validateSchema produces a required issue.

Every @luthor model produces final SchemaValidator $ModelSchema, and a field whose type is another model refers to that model’s schema through forwardRef(). What gets generated shows the whole output.

final user = l.schema({
'email': l.string().email().required(),
'age': l.int().min(18),
});
user.validate(input)+2-3
  1. valid: {'email': '[email protected]'}
  2. valid: {'email': '[email protected]', 'age': 30, 'extra': true}
  3. invalid: {'email': 'bad', 'age': 12}email: email must be a valid email addressage: age must be greater than or equal to 18
  4. invalid: {'age': 30}email: email is required
  5. invalid: 'not a map'value must be a map

The output drops the unknown key:

ValidationSuccess(data: {email: [email protected], age: 30})

Convert valid input with fromJson:

final result = user.validateSchema(json, fromJson: User.fromJson);