dry-schema

v1.14
  1. Introduction
  2. Basics
    1. Built-in predicates
    2. Macros
    3. Type specs
    4. Working with schemas
  3. Optional keys and values
  4. Nested data
  5. Reusing schemas
  6. Params
  7. JSON
  8. Error messages
  9. Advanced
    1. Composing schemas
    2. Custom predicates
    3. Custom types
    4. Filtering
    5. Key maps
    6. Predicate logic
    7. Processor steps
    8. Rule AST
    9. Unexpected keys
  10. Extensions
    1. Hints
    2. Info
    3. JSON Schema
    4. Monads

TOC


Unexpected keys

You can enable special key validation which will provide error messages about unexpected keys in an input. This is useful if you want to be very strict about what your system allows.

In order to use this type of validation, you need to enable it via config:

# Enable it globally
Dry::Schema.config.validate_keys = true


# or per schema
Dry::Schema.Params do
  config.validate_keys = true

  # ...
end

Here's a simple usage example:

require 'dry/schema'

UserSchema = Dry::Schema.Params do
  config.validate_keys = true

  required(:name).filled(:string)

  required(:address).hash do
    required(:city).filled(:string)
    required(:zipcode).filled(:string)
  end

  required(:roles).array(:hash) do
    required(:name).filled(:string)
  end
end

input = {
  foo: 'unexpected',
  name: 'Jane',
  address: { bar: 'unexpected', city: 'NYC', zipcode: '1234' },
  roles: [{ name: 'admin' }, { name: 'editor', foo: 'unexpected' }]
}

UserSchema.(input).errors.to_h
# {
#  :foo=>["is not allowed"],
#  :address=>{:bar=>["is not allowed"]},
#  :roles=>{1=>{:foo=>["is not allowed"]}}
# }