Dynamic form validation with dry-validation gem

There can be situations when we need dynamic validation of incoming params.

For example, we have a form with many fields that are stored in our database. Form fields can be added, deleted and customized by users. We would like to validate this form using convenient dry-validation gem syntax. Unfortunately, in dry-validation there is no way to do this:

 class FormContract < Dry::Validation::Contract option :form_fields params do form_fields.each do |form_field| # form_fields variable is not available in params block required(form_field.name).filled(:string) end end end 

We can validate our form in the following way:

 class FormContractBuilder def self.schema(form_fields) form_contract = Class.new(Dry::Validation::Contract) { params do form_fields.each do |form_field| required(form_field.name).filled(:string) end end } form_contract.new end end FormContractBuilder.schema(form.fields).call(params) 
Do you have a project for us?Get a free quote