How prevent dry-validation from executing a rule if schema validation did not pass?

1.1k Views Asked by At
class PostSchema < Dry::Validation::Contract
  params do
    required(:title).value(:string, size: 20)
    required(:content).value(:string, size: 50)
  end 
  
  rule do 
     # prevent this rule from executing if schema validation did not pass
  end
end

My current work around is to use result.schema_result.success?. Even this is working but I look at the source code at https://github.com/dry-rb/dry-validation/blob/master/lib/dry/validation/result.rb#L41. It is a private API. Does anyone have any idea about this?

1

There are 1 best solutions below

0
On

A rule without any keys specified will always be executed. That's by design. If you want it to not be executed, simply provide which keys it depends on, ie:

rule(:title, :content) do
  # won't be executed unless both title and content passed
  # the schema checks
end