闭社主体 forked from https://github.com/tootsuite/mastodon
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

20 lines
617 B

  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 =~ error.message }
  13. end
  14. end