views:

627

answers:

2

How can I dynamically configure a validation in rails? For EXAMPLE if I have

validates_length_of :name, within => dynamic

The variable "dynamic" will be set by the user. On save, the validation should use the value of the variable "dynamic" to configure the within configuration.

+5  A: 

I don't believe validates_length_of supports dynamic parameters. You'll need to duplicate the behavior in a custom validation.

# in model
def validate
  unless (5..10).member? name.length
    errors.add :name, "must be within 5 to 10 characters"
  end
end

That uses a static range, but you can easily use your own custom range variable.

def validate
  unless some_range.member? name.length
    errors.add :name, "must be within #{some_range.first} to #{some_range.last} characters"
  end
end

You may want to check out my Railscasts episode on conditional validations and Episode 3 in my Everyday Active Record series.

ryanb
Thanks for your answer. I need the dynamic variable on validates_presence_of like this: validates_presence_of :name, :locales => dynamic_array (:locales can be [:en, :de,...] dynamic). The configuration :locales by validates_presence_of comes with the i18n_multi_locales_validations plugin.
phlegx
A: 
validates_inclusion_of :n, :in => 21..30, :message => "can only be between 21 and 30."

via

marcgg