Dave Dave -4 years ago 67
Ruby Question

In Rails, how do I write a validation rule to validate that both fields should be present or neither be?

I'm using Ruby on Rails 5. I have a model with a couple of fields


How do I write a validation rule to specify that if one is present, then the other one must be as well? It is fine if they are both blank but basically they must either be present or neither be present. How do I write a rule for that?

Answer Source

There are two options here. You can either use a conditional validation or write a custom validation to do this check.

With a conditional validation:

validates :first_name, presence: true, if: -> {last_name.present?}

With a custom validation:

validate :both_or_neither_present
# ...
def both_or_neither_present
  # if only one of the fields is present
  if (first_name.present? ^ last_name.present?)
    errors.add(:name, "Only part of the name was given")

With the second one you can write a custom error message. With the first, the error will always be on the :first_name attribute.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download