Travis Rigg
Travis Rigg

Reputation: 15

How do I validate that either one field or another is filled out in Ruby on Rails?

I have contact information. The user needs to fill out at least one of three fields, those fields being their email address, mailing address, or phone number.

How would I do this in Ruby on Rails?

Upvotes: 0

Views: 230

Answers (2)

Justin
Justin

Reputation: 4940

Someone can give you a better answer, but this will do. You can just write your own method to check if those fields are blank. If they are blank, render an error.

validate :at_least_one

def at_least_one
  return unless email.blank? && address.blank? && phone.blank?

  errors.add(:base, 'Error message') # you can add the error to the base or even a particular attribute.
end

Upvotes: 1

nPn
nPn

Reputation: 16768

While what Justin shows may be fine, Rails does provide a formal scheme for doing just this type of thing. It allows you to create a custom validator just like any of the predefined validators.

See "validates_with" for more details, but here is the example from the Rails guide:

class GoodnessValidator < ActiveModel::Validator
  def validate(record)
    if record.first_name == "Evil"
      record.errors[:base] << "This person is evil"
    end
  end
end

class Person < ActiveRecord::Base
  validates_with GoodnessValidator
end

Upvotes: 0

Related Questions