Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby gem to quickly validate partial HTML snippets?

I'm making a customized quasi-CMS in Rails, and we'd like to have one field that is editable as an HTML fragment in code (the admin interface will be using CodeMirror on the frontend). When it's presented to the end user, it will just be html_safe'd and inserted into a div. We trust our content editors not to be malicious, but it would be helpful to ensure they're creating valid HTML so they don't break the page, especially since they're relatively new to coding!

As a first attempt, I'm using Hash.from_xml and rescuing exceptions as a custom validator. But is there a better and/or more-optimized way (i.e. a gem) to check that it is valid HTML?

Thanks!

like image 383
btown Avatar asked Jun 24 '14 20:06

btown


2 Answers

You can use the Nokogiri library (and gem) to create a validator in your model. Using Nokogiri on fragments isn't perfect (so you might want to add the ability to override the validator) but it will catch many obvious errors that might break the page.

Example (assuming your model attribute/field is called 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
like image 53
Jacob Dalton Avatar answered Nov 04 '22 04:11

Jacob Dalton


Instead of validation, perhaps it's worth to use Nokogiri which is capable of fixing markup:

require 'nokogiri'
html = '<div><b>Whoa</i>'
Nokogiri::HTML::DocumentFragment.parse(html).to_html
#=> "<div><b>Whoa</b></div>"
like image 25
skalee Avatar answered Nov 04 '22 06:11

skalee