opensoul.org

Validations on empty (not nil) attributes

February 7, 2007 code 2 min read

One of the first problems that I ran into when I started using Rails was trying to validate the format of attributes that aren’t required. Most of the validations have an :allow\_nil option, but the problem is that when a form is submitted with empty form fields, those fields are empty strings instead of nil values. So the validation fails because the attribute is not nil.

For example, here’s a Person model with a validation on :social\_security\_number, an optional attribute:

class Person < ActiveRecord::Base
  validates_format_of :social_security_number,
    :with => /\d{3}[-]?\d{2}[-]?\d{4}/, :allow_nil => true
end

When this model is used in a form, validation will fail if the social security number field is left blank, even though :allow\_nil is set to true.

The solution

It turns out that the solution is really simple: a before\_validation callback that just goes through and sets all the empty attributes to nil.

class ActiveRecord::Base
  before_validation :clear_empty_attrs
protected
  def clear_empty_attrs
    @attributes.each do |key,value|
      self[key] = nil if value.blank?
    end
  end
end

I’ve packaged this little nugget into a plugin. Install it and go on your merry validating way.

script/plugin install -x git://github.com/collectiveidea/clear_empty_attributes.git
This content is open source. Suggest Improvements.

@bkeepers

avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.