Non-tech founder’s guide to choosing the right software development partner Download Ebook
Home>Blog>Dynamic form validation with dry-validation gem

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)

Discover More Reads

Recent Projects

We take pride in creating applications that drive growth and evolution, from niche startups to international companies.

Let’s Build Something Great Together

Let’s discuss your project and see how Ruby on Rails can be your competitive advantage.

*By submitting this form, you agree with JetRockets’ Privacy Policy