How to validate optional fieldset which becomes mandatory?

Hi,

I am posting here because a re-read of my ‘Agile’ book and quick google
around didn’t give me any obvious clues, but I apologise if this has
already been asked and answered before…

I have an ‘invoice address’ fieldset in a form which is entirely
optional,
however, should the user fill any one of the fields then they
effectively
all become mandatory and I need to validate the presence of the required
fields (I need to make sure that at least the first line of address,
city
and zip are filled).

What is the best way to do this? I am new to Rails and still finding my
feet but I appreciate that there is probably more than one way of
approaching this?

TIA,

Matt.

Matthew L. wrote:

Hi,

I am posting here because a re-read of my ‘Agile’ book and quick google
around didn’t give me any obvious clues, but I apologise if this has
already been asked and answered before…

I have an ‘invoice address’ fieldset in a form which is entirely
optional,
however, should the user fill any one of the fields then they
effectively
all become mandatory and I need to validate the presence of the required
fields (I need to make sure that at least the first line of address,
city
and zip are filled).

What is the best way to do this? I am new to Rails and still finding my
feet but I appreciate that there is probably more than one way of
approaching this?

TIA,

Matt.

AWDW page 267 describes the “validate” method, where you can put any
custom validations that don’t fit the higher-level validations provided.

So you can do this:

class Invoice < ActiveRecord::Base
def validate
if address or city or zip
errors.add_to_base(“You must specify address, city and zip for
this invoice”) unless (address and city and zip)
end
end
end

That’s a rough idea of how you could do it. Hope it helps!

Jeff

I addition to Jeff’s advise, I would put address in separate table/class
where all kinds of addresses go. So you will have a link from your
Invoice to the Address, as BillingAddress, ShipAddress etc. This will
also allow to use standard validators.

I addition to Jeff’s advise, I would put address in separate table/class
where all kinds of addresses go. So you will have a link from your
Invoice to the Address, as BillingAddress, ShipAddress etc. This will
also allow to use standard validators.

Thanks guys. That was the push I needed to get it working and a big
“D’oh!” for not realising I should be using validate to get this done.

Thanks!