Validations Based On Conditions

21 July 2007

Sometimes i have ran into a situation where there was a need to validate a new record depending upon which method was used. For example I was capturing data for an event which had both domestic and international leads. There were different criteria for the two sets of data.

For eg: I needed to validate presence of state, cost center for US leads and ignore those for international leads.

So i needed to figure out separate ways to handle the validations. Here is how I implemented it.

I defined two methods in my model: usa_validation? and international_validation?

# validations only specific to usa leads
  attr_accessor :usa_validation
 
  def usa_validation?
    return usa_validation
  end
 
  def usa_validation=(value)
    @usa_validation = value
  end
 
  validates_presence_of :region, :if => :usa_validation?
  validates_presence_of :cost_center, :if => :usa_validation?
 
  # validations only specific to international leads
  attr_accessor :international_validation
 
  def international_validation?
    return international_validation
  end
 
  def usa_validation=(value)
    @usa_validation = value
  end
 
  validates_presence_of :country, :if => :international_validation?

In my controller i set the flag to true for US or international depending upon the case.

def capture_usa_lead
    @lead = Lead.new(params[:lead])
    @lead.usa_validation =  true
    if @lead.save
      #display message
    else
      render  :layout => "lead", :partial => "usa_form"
    end
  end
  def capture_international_lead
    @lead = Lead.new(params[:lead])
    @lead.international_validation = true
    if @lead.save
            #display message
    else
      render  :layout => "lead", :partial => "international_form"
    end
  end