Class: ActiveModel::Validations::HtmlValidator

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

Constant Summary collapse

HTML5_TAGS =
%w(section nav article aside header footer figure figcaption time mark ruby rt rp wbr embed video audio source canvas datalist optgroup option textarea keygen output progress meter details summary command menu )

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ HtmlValidator

Returns a new instance of HtmlValidator.



12
13
14
15
# File 'lib/rails_html_validator/html_validator.rb', line 12

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

Instance Method Details

#ignore_html5_tag_errors(errors) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/rails_html_validator/html_validator.rb', line 34

def ignore_html5_tag_errors errors
  checker = HTML5_TAGS.map { |tag| "Tag #{tag} invalid"}
  regexp = Regexp.union(checker)
  errors.select do |error|
    !(regexp === error.message)
  end
end

#validate_each(record, attribute, value) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rails_html_validator/html_validator.rb', line 17

def validate_each(record, attribute, value)
  html = ::Nokogiri.HTML(value) {|config| config.strict}
  errors = ignore_html5_tag_errors(html.errors)
  if errors.present?
    record.errors.add(attribute, I18n.t("errors.messages.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