Forum: Ruby on Rails Validate presence of 1 of 2 fields

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Seth B. (Guest)
on 2007-05-04 16:48
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
J. Yaunches (Guest)
on 2007-05-04 18:56
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."
Eden L. (Guest)
on 2007-05-05 08:23
(Received via mailing list)
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.
Eden L. (Guest)
on 2007-05-05 08:26
(Received via mailing list)
> 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 "&&"
Seth B. (Guest)
on 2007-05-05 18:52
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.
Eden L. (Guest)
on 2007-05-06 08:56
(Received via mailing list)
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. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.