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

  1. Handling empty strings

Params

Probably the most common use case is to validate HTTP params. This is a special kind of a validation for a couple of reasons:

For that reason, dry-schema ships with Params schemas:

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

errors = schema.call('email' => '', 'age' => '18').errors

puts errors.to_h.inspect
# {
#   :email => ["must be filled"],
#   :age => ["must be greater than 18"]
# }

Params-specific value coercion is handled by the hash type from dry-types. It is built automatically for you based on the type specs and used prior to applying the validation rules

Handling empty strings

Your schema will automatically coerce empty strings to nil, provided that you allow a value to be nil:

schema = Dry::Schema.Params do
  required(:email).filled(:string)
  required(:age).maybe(:integer)
  required(:tags).maybe(:array)
end

result = schema.call('email' => 'jane@doe.org', 'age' => '', 'tags' => '')

puts result.to_h
# {:email=>'jane@doe.org', :age=>nil, :tags=>nil}

Your schema will automatically coerce empty strings to an empty array:

schema = Dry::Schema.Params do
  required(:tags).value(:array)
end

result = schema.call('tags' => '')

puts result.to_h
# {:email=>'jane@doe.org', :age=>nil, :tags=>[]}