Cecille Manalang
Cecille Manalang

Reputation: 223

Activerecord field validation one after the other

I would like to know how do you validate a field after passing other validations, for example, I have:

validates_numericality_of :field
validates_inclusion_of :field (after validating field's numericality)

Thanks in advance.

Upvotes: 0

Views: 183

Answers (1)

shime
shime

Reputation: 9018

You have to write a custom validation method for this.

This is how I would do it:

validate :custom_inclusion

private

def custom_inclusion
    range = (1..100)
    begin
      Kernel.float(field)
    rescue ArgumentError
      errors.add(:field,"is not a number") and return
    end

    if !(range.min < field.to_i && range.max > field.to_i)
      errors.add(:field,"is not between #{range.min} and #{range.max}")
    end
end

where field is a model attribute you want to validate.

Upvotes: 1

Related Questions