Mathieu
Mathieu

Reputation: 4787

Rails 4 active record validation - Conditionally validate interdependent presence of 4 attributes

I have a form with 10 attributes.

Among them I have 4 attributes which I need to apply what I'd call a"mutually conditional presence" Active Record validation. these attributes are

It means that if the user fills ONE of them then ALL the others have to be present

So far I have only be able to say that if the user fills the first attribute "address line 1" then all the others must be present.

But it does not validate that all the MUTUAL presences in all possible combinations. For example if the user lets 'address line 1' empty but fills zipcode and leaves the other three empty, I want active recoird not to validate the form as he then should have been asked to fill the other three attributes. And so on with each of the attibutes.

How to do this?

Here is my current code

spec/models/users

validates :address_line_1,
              presence: true,
              length: { maximum: 100,
                        minimum: 3 }
  validates :zipcode,
              presence: true, if: :address_line_1?,
              length: { maximum: 20,
                        minimum: 4} 
  validates :state,
              presence: true, if: :address_line_1?,                  
  validates :country,
              presence: true, :address_line_1?,                  
              length: { maximum: 50}  

Upvotes: 4

Views: 144

Answers (1)

dre-hh
dre-hh

Reputation: 8044

Just replace :address_line?condition with a check for one of the filled out fields:

  validates :address_line_1,
              presence: true, if: :address_entered?,
              length: { maximum: 100,
                        minimum: 3 }
  validates :zipcode,
              presence: true, if: :address_entered?,
              length: { maximum: 20,
                        minimum: 4


 validates :state,
              presence: true, if: :address_entered?,
  validates :country,
              presence: true, if: :address_entered?,
              length: { maximum: 50}

  def address_entered?
    address_line_1.present? || zipcode.present? || state.present? || country.present?
  end

Upvotes: 6

Related Questions