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. Conjunction (and)
  2. Disjunction (or)
  3. Implication (then)
  4. Exclusive Disjunction (xor)
  5. Operator Aliases

Predicate logic

Schema DSL allows you to define validation rules using predicate logic. All common logic operators are supported and you can use them to compose rules. This simple technique is very powerful as it allows you to compose validations in such a way that invalid state will not crash one of your rules. Validation is a process that always depends on specific conditions, in that sense, dry-schema schemas have rules that are always conditional, they are executed only if defined conditions are met.

This document explains how rule composition works in terms of predicate logic.

Conjunction (and)

Dry::Schema.Params do
  required(:age) { int? & gt?(18) }
end

:age rule is successful when both predicates return true.

Disjunction (or)

Dry::Schema.Params do
  required(:age) { nil? | int? }
end

:age rule is successful when either of the predicates, or both return true.

Implication (then)

Dry::Schema.Params do
  required(:age) { filled? > int? }
end

:age rule is successful when filled? returns false, or when both predicates return true.

Optional keys are defined using implication, that's why a missing key will not cause its rules to be applied and the whole key rule will be successful

Exclusive Disjunction (xor)

Dry::Schema.Params do
  required(:status).value(:integer) { even? ^ lt?(0) }
end

:status is valid if it's either an even integer, or it's value is less than 0.

Operator Aliases

Logic operators are actually aliases, use full method names at your own convenience: