Class: ActiveModel::Validations::HtmlValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/html_validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ HtmlValidator

Returns a new instance of HtmlValidator.


10
11
12
13
# File 'lib/html_validator.rb', line 10

def initialize(options)
  options.reverse_merge!(exclude_tags: [])
  super(options)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/html_validator.rb', line 15

def validate_each(record, attribute, value)
  html = ::Nokogiri.HTML(value) {|config| config.strict}
  if html.errors.present?
    record.errors.add(attribute, I18n.t("errors.messages.html"))
    html.errors.each do |err|
      record.errors.add(attribute, err.message)
    end
  end

  options.fetch(:exclude_tags).each do |tag|
    if html.css(tag.to_s).present?
      record.errors.add(attribute, I18n.t("errors.messages.html_tag", tag: tag))
    end
  end
end