validate snippets

Validating HTML Emails with Nokogiri, Tidy, and validator.w3.org

Tagged devise, validate, tidy, nokogiri, emails  Languages ruby
# We're validating the HTML generated by the Devise mailer
user = User.new email: 'xxx@xxx'
mail = Devise.mailer.confirmation_instructions(user, self).deliver
html = mail.html_part.body.to_s

Validate with tidy:

File.open('/tmp/html-validation.html', 'w') { |f| f << html }
unless system "tidy -errors -q -f /tmp/validation-errors.txt /tmp/html-validation.html"
  fail "Validation failed:\n #{File.read('/tmp/validation-errors.txt')}"
end

Remember to install tidy first:

$ sudo apt-get install tidy

Validate with Nokogiri is not so fun or accurate:

# Validate XML
doc = Nokogiri.XML(html)
doc.errors

# Validate against a schema, if you want
xsd = Nokogiri::XML::Schema(open('http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd'))
xsd.validate(doc)

For validation with w3.org, see this script

Validating HTML with validator.w3.org and Ruby

Tagged w3, html, validate, ruby  Languages ruby
require "net/http"

def validate(html)
  response = Net::HTTP.start("validator.w3.org") do |r|
    query = "output=json&fragment=" + CGI.escape(html)
    r.post2("/check", query)
  end
  if "Invalid" == response["x-w3c-validator-status"]
    File.open('/tmp/html-validation.html', 'w') { |f| f << html }
    JSON.parse(response.body)
  end
end

# List all validation errors
html = File.read('/tmp/html-validation.html')
if errors = validate(html)
  puts errors
end