Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate presence of one field or another (XOR)

How do I validate the presence of one field or another but not both and at least one ?

like image 337
Ben Orozco Avatar asked Jan 25 '10 17:01

Ben Orozco


1 Answers

Your code will work if you add conditionals to the numericality validations like so:

class Transaction < ActiveRecord::Base     validates_presence_of :date     validates_presence_of :name      validates_numericality_of :charge, allow_nil: true     validates_numericality_of :payment, allow_nil: true       validate :charge_xor_payment    private      def charge_xor_payment       unless charge.blank? ^ payment.blank?         errors.add(:base, "Specify a charge or a payment, not both")       end     end  end 
like image 134
semanticart Avatar answered Sep 22 '22 14:09

semanticart