Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validation that one value does not equal another

Is there a way to validate that one text_field does not equal another before saving record? I have two text_fields with integers in them and they cannot be identical for record to be valid.

like image 791
Meltemi Avatar asked Feb 23 '12 19:02

Meltemi


2 Answers

You can add a custom validation:

class Something
  validate :fields_a_and_b_are_different

  def fields_a_and_b_are_different
    if self.a == self.b
      errors.add(:a, 'must be different to b')
      errors.add(:b, 'must be different to a')
    end
  end

That will be called every time your object is validated (either explicitly or when you save with validation) and will add an error to both of the fields. You might want an error on both fields to render them differently in the form.

Otherwise you could just add a base error:

errors.add(:base, 'a must be different to b')
like image 169
Shadwell Avatar answered Nov 01 '22 11:11

Shadwell


In your model:

validate :text_fields_are_not_equal

def text_fields_are_not_equal
  self.errors.add(:base, 'Text_field1 and text_field2 cannot be equal.') if self.text_field1 == self.text_field2
end
like image 5
Veraticus Avatar answered Nov 01 '22 13:11

Veraticus