I am writing a simple CMS in Rails 4. And I am storing my articles in database as text strings that contains HTML code (not necessary).
Anyway, I need a method to check before saving, if the text of the article is valid HTML or nor (considering that the article is not full HTML document, but the part of it, without DOCTYPE and other stuff). Something like this: https://validator.w3.org/#validate_by_input+with_options ("Validate HTML fragment"), but working inside my Rails application as validation method of the model, so if my markup is wrong, it should not save the article and show the error message instead.
How can I achieve this?
So I figured out how to achieve this using w3c_validators
gem.
gem 'w3c_validators'
to Gemfile and run bundle install
.Change model. I've added a custom validation method to validate HTML, like this:
class Article < ActiveRecord::Base
validate :valid_html
def valid_html
@validator = MarkupValidator.new
html = "<!DOCTYPE html><html><head><title>title</title></head><body>#{text}</body></html>"
results = @validator.validate_text(html)
if results.errors.length > 0
results.errors.each do |err|
errors.add(:text, err.to_s)
end
end
end
end
(I need to wrap my code into HTML and BODY tags and add some more tags, because I don't store full HTML in my DB, only partials).