Ruby gem for quick validation of partial HTML snippets?

I am making custom quasi-CMS in Rails, and we would like to have one field that can be edited as an HTML snippet in the code (admin interface will use CodeMirror on the interface). When it is presented to the end user, it will simply be html_safe'd' and inserted into the div. We trust our content editors not to be malicious, but it would be useful to make sure that they create the correct HTML so that they do not break the page, especially since they are relatively new to coding!

As a first attempt, I use Hash.from_xmland throw exceptions as a custom validator. But is there a better and / or more optimized way (like a gem) to verify that it is valid HTML?

Thank!

+4
source share
4 answers

Instead of checking, it might be worth using Nokogiri, which can capture markup:

require 'nokogiri'
html = '<div><b>Whoa</i>'
Nokogiri::HTML::DocumentFragment.parse(html).to_html
#=> "<div><b>Whoa</b></div>"
+5
source

Nokogiri ( gem), . Nokogiri ( ), , .

( / content):

validate :invalid_html?

def invalid_html?
  doc = Nokogiri::HTML(self.content) do |config|
    config.strict
  end
  if doc.errors.any?
    errors.add(:base, "Custom Error Message")
  end
end
+8
+1

Source: https://habr.com/ru/post/1545900/


All Articles