Skip to content

Commit

Permalink
Adding validator for hex colors that adheres to HTML 5 simple-color s…
Browse files Browse the repository at this point in the history
…pec.
  • Loading branch information
bamnet committed Jun 3, 2010
1 parent 66e9677 commit 09a34f0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions app/models/layer.rb
@@ -1,2 +1,5 @@
class Layer < ActiveRecord::Base

# Validations
validates :color, :hex_color => true
end
13 changes: 13 additions & 0 deletions lib/hex_color_validator.rb
@@ -0,0 +1,13 @@
# Validates a hexidecimal 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

0 comments on commit 09a34f0

Please sign in to comment.