Last Updated: February 25, 2016
·
6.253K
· michaelcarter

CSS hex color validation in Rails

An easy to use CSS hex color validator for Rails. Simply pop this into a css_hex_color_validator.rb file in app/validators/.

class CssHexColorValidator < ActiveModel::EachValidator

  def validate_each(object, attribute, value)
    unless value =~ /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i
      object.errors[attribute] << (options[:message] || "must be a valid CSS hex color code")
    end
  end

end

And use like so:

class SomeModel < ActiveRecord::Base

validates :link_color, :css_hex_color => true

You can read more about custom validations in the Active Record Validations and Callbacks Rails documentation, or get a copy of this in gist form over on GitHub.