Ruby on Rails validation for two connected fields
On a recent Ruby on Rails project I needed to validate an address form so that when submitted, either the house number or the house name or both were present.
Although this post nearly did it, I had to modify Eric’s code slightly and this is the result (taken from the address.rb model file)
This also shows how I validate UK postcodes. Can’t remember where I found that regular expression but
I am pretty sure I did not make it up myself !
class Address < ActiveRecord::Base belongs_to :user, :validate => true belongs_to :property belongs_to :guest validates_presence_of :town, :message => 'Town is missing' validates_presence_of :street1, :message => 'Street1 is missing' validates_presence_of :postcode, :message => 'Postcode is missing ' validates_format_of :postcode, :with => /^([A-PR-UWYZ][A-HK-Y0-9][A-HJKS-UW0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLNP-UW-Z]{2})$/, :message => "Invalid postcode " def self.validate_at_least_one_of(*attrs) configuration = { :message => "One of #{attrs.to_sentence} must be set", :on => :save } configuration.update(attrs.pop) if attrs.last.is_a?(Hash) error_key = "" # The key to put in your view should be xxx_yyy_ where xxx and # yyy are attrs[0], attrs[1] etc. attrs.each do |attrib| error_key = error_key + attrib.to_s + "_" end options = configuration send(validation_method(options[:on] || :save)) do |record| found_non_blank = false attrs.each do |attr| value = record.send(attr) if !value.blank? found_non_blank = true end end # attrs.each if ! found_non_blank record.errors.add(error_key, configuration[:message]) end end # send end validate_at_least_one_of :house_number, :house_name, :on => :save end
Then in the form itself, I used the following code to display any error message. (The address model belongs to the user model)
<div class="error_field"> <%= if @user.address != nil then @user.address.errors.on :house_number_house_name_ end %> </div>