class ActiveModel::Validations::HtmlValidator

Constants

HTML5_TAGS

Public Class Methods

new(options) click to toggle source
Calls superclass method
# File lib/rails_html_validator/html_validator.rb, line 12
def initialize(options)
  options.reverse_merge!(exclude_tags: [])
  super(options)
end

Public Instance Methods

ignore_html5_tag_errors(errors) click to toggle source
# 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) click to toggle source
# 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