color_validator.rb 1.0 KB

123456789101112131415161718192021
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class Validations::ColorValidator < ActiveModel::EachValidator
  3. REGEXP = {
  4. RGB: %r{^rgb\((((((((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5]),\s?)){2}|((((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5])\s)){2})((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5]))|((((([1-9]?\d(\.\d+)?)|100|(\.\d+))%,\s?){2}|((([1-9]?\d(\.\d+)?)|100|(\.\d+))%\s){2})(([1-9]?\d(\.\d+)?)|100|(\.\d+))%))\)$}i,
  5. HSL: %r{^hsl\(((((([12]?[1-9]?\d)|[12]0\d|(3[0-6]\d))(\.\d+)?)|(\.\d+))(deg)?|(0|0?\.\d+)turn|(([0-6](\.\d+)?)|(\.\d+))rad)((,\s?(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2}|(\s(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2})\)$}i,
  6. HEX: %r{^#([\da-f]{3}){1,2}$}i
  7. }.freeze
  8. def validate_each(record, attribute, value)
  9. return if color?(value)
  10. record.errors.add attribute, (options[:message] || __('is not a color. Only Hex, RGB and HSL colors are supported.'))
  11. end
  12. def color?(value)
  13. sanitized_value = value.to_s.strip.gsub(', ', ',')
  14. REGEXP.values.any? { |regexp| regexp.match? sanitized_value }
  15. end
  16. end