Permalink
Browse files

Adding validator for hex colors that adheres to HTML 5 simple-color s…

…pec.
  • Loading branch information...
bamnet committed Jun 3, 2010
1 parent 66e9677 commit 09a34f07d83b1835201aadfa9aa1d61734c44d25
Showing with 16 additions and 0 deletions.
  1. +3 −0 app/models/layer.rb
  2. +13 −0 lib/hex_color_validator.rb
View
@@ -1,2 +1,5 @@
class Layer < ActiveRecord::Base
+
+ # Validations
+ validates :color, :hex_color => true
end
View
@@ -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.