7

I would like to create a custom validation method within my model and use some existing validators (specifically, validates_numericality_of) within the custom validation method.

Is this possible? If so, how do I do it?

For some context: We are using a non-ActiveRecord ORM that has an attribute that is a Hash. I want to perform validations on stuff inside the hash. If there is a way to do that, like validates_numericality_of :my_attribute.:subattribute or something, that would be fine too.

Thank you.

nc.
  • 7,179
  • 5
  • 28
  • 38
  • I have a similar situation. A pattern exists in my application where a field must be present *if* a condition is met and absent *unless* the condition is met. So I want my custom validator to use PresenceValidator and AbsenceValidator. Did you ever solve your problem? – Samo Nov 13 '14 at 05:57
  • Hi @samo, I solved my problem by writing a custom validator that implemented my own validations similar to `validates_numericality_of`. I will take a look at your proposed solution when I get a chance. – nc. Nov 13 '14 at 23:31

1 Answers1

8

I believe this should work for you.

class MyCustomValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    validator = ActiveModel::Validations::NumericalityValidator.new(
      :greater_than_or_equal_to => options[:min],
      :less_than_or_equal_to => options[:max],
      :attributes => value[:some_attribute]
    )
    validator.validate(record)
  end
end

You could use it like this:

validates(
  :my_pseudo_attribute,
  :my_custom => {
    :min => 0,
    :max => 100
  }
)

def my_pseudo_attribute
  {
    :some_attribute => 'foo'
  }
end
Samo
  • 8,202
  • 13
  • 58
  • 95