Matthew Law
2006-Apr-10 08:11 UTC
[Rails] 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.
Jeff Coleman
2006-Apr-10 08:21 UTC
[Rails] Re: How to validate optional fieldset which becomes mandator
Matthew Law 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 -- Posted via http://www.ruby-forum.com/.
sergey podlesnyi
2006-Apr-10 09:09 UTC
[Rails] Re: How to validate optional fieldset which becomes mandator
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. -- Posted via http://www.ruby-forum.com/.
Matthew Law
2006-Apr-10 11:52 UTC
[Rails] Re: How to validate optional fieldset which becomes mandator
> 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!