Meltemi
Meltemi

Reputation: 38359

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.

Upvotes: 7

Views: 3022

Answers (3)

stephan.com
stephan.com

Reputation: 1518

more fun:

  validates :a, exclusion: { in: ->(thing) { [thing.b] } }

Though of course this isn't terribly readable, but it's elegant - we're leveraging the exclusion validation with a proc to prevent the values from being equal. A more verbose approach might be preferred by some, but I'm a fan of brevity - code that doesn't exist can't have bugs. Plus, this will get its error message the default rails location, which may be convenient for i18n purposes.

(better?)

Upvotes: 0

Shadwell
Shadwell

Reputation: 34784

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')

Upvotes: 10

Veraticus
Veraticus

Reputation: 16084

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

Upvotes: 5

Related Questions