dry-schema: Explicitly mark that a param can be ignored if nil

Given there’s a search form, where all fields are optional, and a validation schema that receives the form raw data via rack.

As we know, the form will be submitted with empty strings as values for empty fields.

Extremely simplified, the params could look something like:

Params = Dry::Validation.Form do
  optional(:date).maybe(:date?) # or required, as it's a form, it will be set anyway
end

So, when the form submits “” for the date param, the validation output will look like { date: nil }, and we have to handle this nil value somewhere.

Is there any way to explicitly say that this param can be ignored if nil? Like “ok, I know it can be empty or nil, but if it is, please just don’t put it in the output”, so that the output would look like {} and we’d not have to handle the nil value elsewhere.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 2
  • Comments: 15 (14 by maintainers)

Commits related to this issue

Most upvoted comments

Closing because it can be done via an after hook now:

dry-schema> s = params do
dry-schema*>   before(:rule_applier) do |result|
dry-schema*>     result.replace(result.to_h.compact)
dry-schema*>   end  
dry-schema*>   
dry-schema*>   required(:name).filled(:string)
dry-schema*>   required(:age).maybe(:integer)
dry-schema*> end  
=> #<Dry::Schema::Params keys=["name", "age"] ... >
dry-schema> s.(name: "jane", age: "").to_h
=> {:name=>"jane"}

Sorry, I meant #190 😃