html_validator.rb 622 B

1234567891011121314151617181920
  1. # frozen_string_literal: true
  2. class HtmlValidator < ActiveModel::EachValidator
  3. ERROR_RE = /Opening and ending tag mismatch|Unexpected end tag/
  4. def validate_each(record, attribute, value)
  5. return if value.blank?
  6. errors = html_errors(value)
  7. record.errors.add(attribute, I18n.t('html_validator.invalid_markup', error: errors.first.to_s)) unless errors.empty?
  8. end
  9. private
  10. def html_errors(str)
  11. fragment = Nokogiri::HTML.fragment(options[:wrap_with] ? "<#{options[:wrap_with]}>#{str}</#{options[:wrap_with]}>" : str)
  12. fragment.errors.select { |error| ERROR_RE.match?(error.message) }
  13. end
  14. end