Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Dynamic Validation

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.

like image 287
phlegx Avatar asked Aug 03 '09 16:08

phlegx


1 Answers

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.

like image 105
ryanb Avatar answered Nov 04 '22 06:11

ryanb