Jun 032010
 

I’m working on adhering to the HTML 5 standard for things whenever possible in Flagship Geo.  While I haven’t gone all-out just yet and completely standardized things, I recently spent a few minutes working on code to help validate colors.

If you had asked me over the weekend if I care a lot about web-colors I would have said no, but then I discovered a bunch of stuff in the HTML 5 about colors.  There is a special “color” input box (not yet implemented anywhere) which is suppose to help people select colors and there is a pretty thorough section on how to validate what belongs in an official color box.

Since validators in Rails 3 are much more straightforward to implement, I took a few minutes to toss one together that validates simple color strings, i.e those hexadecimal strings that start with a pound sign.  If you’re looking to do something like this in your application, here’s how:

lib/hex_color_validator.rb

# Validates a hexadecimal color string as defined in the HTML 5 spec.
# This validator only works for the simple case and does not support
# any legacy formats. See http://dev.w3.org/html5/spec/Overview.html#valid-simple-color
# for the format spec.
class HexColorValidator < ActiveModel::EachValidator
  # Verifies a color string is 7 characters long and contains
  # only hex values after the pound sign.
  def validate_each(object, attribute, value)
    unless value =~ /^#[0-9a-fA-F]{6}$/
      object.errors[attribute] << (options[:message] || " is not a properly formatted color string")
    end
  end
end

… paired with …
app/model/layer.rb

class Layer < ActiveRecord::Base
 
 # Validations
 validates :color, :hex_color => true
end

In my example, I’m validating the color attribute that exists on the Layer model. You can view the commit on GitHub if you’d like.