Validate presence of 1 of 2 fields

I have a model with a home and work phone number and I just want to
validate that one of the two are present and correct. Would I have to
write my own validation method? If so what is wrong with below?:

def validate
errors.add(“Either home email or work email need to be entered.”)
unless home_email.nil? or work_email.nil?
end

Seth B. wrote:

I have a model with a home and work phone number and I just want to
validate that one of the two are present and correct. Would I have to
write my own validation method? If so what is wrong with below?:

def validate
errors.add(“Either home email or work email need to be entered.”)
unless home_email.nil? or work_email.nil?
end

It would be simpler to do something like:

validates_presence_of :home_email, :work_email, :message => “Either home
email or work email need to be entered.”

Seth B. wrote:

def validate
errors.add(“Either home email or work email need to be entered.”)
unless home_email.nil? or work_email.nil?
end

Overriding validate directly isn’t recommended. Try:

validate_on_create do |record|
record.errors.add("", “Either home email or work email need to be
entered.”) if record.home_email.blank? || record.work_email.blank?
end

J. Yaunches wrote:

validates_presence_of :home_email, :work_email, :message => “Either home
email or work email need to be entered.”

That would trigger an error unless both are provided. I think Seth
wants an error only if none are given.

validate_on_create do |record|
record.errors.add("", “Either home email or work email need to be
entered.”) if record.home_email.blank? || record.work_email.blank?
end

Sorry change the “||” in the if statement to “&&”

Actually I wanted to test that at least one are provided.

That would trigger an error unless both are provided. I think Seth
wants an error only if none are given.

validate_on_create do |record|
record.errors.add(“Home or work email”, “need to be entered.”) if
record.home_email.blank? && record.work_email.blank?
end

should work then. Your original ‘unless’ expression was saying they
both needed to be provided.

On May 5, 10:52 pm, Seth B. [email protected]