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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With