Skip to content

Instantly share code, notes, and snippets.

@kellishaver
Created October 21, 2013 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellishaver/7084804 to your computer and use it in GitHub Desktop.
Save kellishaver/7084804 to your computer and use it in GitHub Desktop.
Validates a hexadecimal color value
class HexColorValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || 'is not a valid colour value') unless self.class.matches?(value)
end
def self.matches?(value)
return false unless value
/\A#(?:[0-9a-f]{3})(?:[0-9a-f]{3})?\z/i.match(value).nil? ? false : true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment