6

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.

phlegx
  • 2,618
  • 3
  • 35
  • 39

1 Answers1

13

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
  • 16,227
  • 5
  • 51
  • 46
  • 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 Aug 03 '09 at 17:08