This repository has been archived on 2024-06-09. You can view files and clone it, but cannot push or open issues/pull-requests.
2019-03-23 14:07:04 +01:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class HtmlValidator < ActiveModel::EachValidator
|
2019-04-10 03:34:16 +02:00
|
|
|
ERROR_RE = /Opening and ending tag mismatch|Unexpected end tag/
|
|
|
|
|
2019-03-23 14:07:04 +01:00
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
return if value.blank?
|
2019-04-10 03:34:16 +02:00
|
|
|
|
2019-03-26 17:33:26 +01:00
|
|
|
errors = html_errors(value)
|
2019-04-10 03:34:16 +02:00
|
|
|
|
|
|
|
record.errors.add(attribute, I18n.t('html_validator.invalid_markup', error: errors.first.to_s)) unless errors.empty?
|
2019-03-23 14:07:04 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2019-03-26 17:33:26 +01:00
|
|
|
def html_errors(str)
|
2019-04-10 03:34:16 +02:00
|
|
|
fragment = Nokogiri::HTML.fragment(options[:wrap_with] ? "<#{options[:wrap_with]}>#{str}</#{options[:wrap_with]}>" : str)
|
|
|
|
fragment.errors.select { |error| ERROR_RE =~ error.message }
|
2019-03-23 14:07:04 +01:00
|
|
|
end
|
|
|
|
end
|