dry-types

v1.8 v1.7
  1. Introduction
  2. Getting Started
  3. Built-in Types
  4. Type Attributes
  5. Default Values
  6. Fallbacks
  7. Constraints
  8. Hash Schemas
  9. Array With Member
  10. Enum
  11. Map
  12. Combining Types
    1. Intersection
    2. Sum
  13. Custom Types
  14. Custom Type Builders
  15. Extensions
    1. Maybe
    2. Monads

TOC


Constraints

You can create constrained types that will use validation rules to check that the input is not violating any of the configured constraints. You can treat it as a lower level guarantee that you're not instantiating objects that are broken.

All types support the constraints API, but not all constraints are suitable for a particular primitive, it's up to you to set up constraints that make sense.

Under the hood it uses dry-logic and all of its predicates are supported.

string = Types::String.constrained(min_size: 3)

string['foo']
# => "foo"

string['fo']
# => Dry::Types::ConstraintError: "fo" violates constraints

email = Types::String.constrained(
  format: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
)

email["jane@doe.org"]
# => "jane@doe.org"

email["jane"]
# => Dry::Types::ConstraintError: "jane" violates constraints