Class: HtmlSafetyValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/html_safety_validator.rb

Overview

HtmlSafetyValidator

Validates that a value does not contain HTML or other unsafe content that could lead to XSS. Relies on Rails HTML Sanitizer: github.com/rails/rails-html-sanitizer

Example:

class Group < ActiveRecord::Base
  validates :name, presence: true, html_safety: true
end

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.error_messageObject



23
24
25
# File 'app/validators/html_safety_validator.rb', line 23

def self.error_message
  _("cannot contain HTML/XML tags, including any word between angle brackets (&lt;,&gt;).")
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



17
18
19
20
21
# File 'app/validators/html_safety_validator.rb', line 17

def validate_each(record, attribute, value)
  return if value.blank? || safe_value?(value)

  record.errors.add(attribute, self.class.error_message)
end