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
endAnd use like so:
class SomeModel < ActiveRecord::Base
validates :link_color, :css_hex_color => trueYou 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.
Written by Mike Carter
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #Css 
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#

 
 
 
 
