How to set default value for Dry::Validation.Params scheme?

2.7k Views Asked by At

I have next scheme

Dry::Validation.Params do
  optional(:per_page).filled(:int?, lteq?: 1000)
  optional(:page).filled(:int?)
end

If I pass empty hash for validation I get empty output but I want to set default values for my data.

I tried Dry::Types.default but it does not add default values in output. That's what I tried.

Dry::Validation.Params do
  optional(:per_page).filled(Dry::Types['strict.integer'].default(10), lteq?: 1000)
  optional(:page).filled(:int?)
end

Is it possible to do what I want?

2

There are 2 best solutions below

0
On

You can do something like this:

optional(:per_page).filled(Types::Integer.constructor { _1 || 10 })

Or define your own fallback strategy as here https://github.com/dry-rb/dry-types/pull/410

optional(:per_page).filled(Types::Integer.constructor { |input, type| type.(input) { 10 } })
0
On

The Dry::Validation has not this purpose.

I recommend you to use dry-initializer on your params before pass it to the validation.