Basics

Here's a basic example where we validate the following things:

  • The input must have a key called :email
    • Provided the email key is present, its value must be filled
  • The input must have a key called :age
    • Provided the age key is present, its value must be an integer and it must be greater than 18

This can be easily expressed through the DSL:

require 'dry-schema'

schema = Dry::Schema.Params do
  required(:email).filled(:string)
  required(:age).filled(:integer, gt?: 18)
end

schema.call(email: 'jane@doe.org', age: 19)
# #<Dry::Schema::Result{:email=>"jane@doe.org", :age=>19} errors={}>

schema.call("email" => "", "age" => "19")
# #<Dry::Schema::Result{:email=>"", :age=>19} errors={:email=>["must be filled"]}>

When you apply this schema to an input, 3 things happen:

  1. Input keys are coerced to symbols using schema's key map
  2. Input values are coerced based on type specs
  3. Input keys and values are validated using defined schema rules

Learn more

octocatEdit on GitHub