Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

HTML validation for dynamic pages

5.00/5 (2 votes)
6 Jul 2014CPOL2 min read 9.3K  
After modifying or creating a web page using jQuery, we sometimes need to validate the HTML

Introduction

Yes, it is true: for business reasons some of us need to develop web pages that work on IE6, 7, and 8 as well as modern browsers. Making sure those old browsers don't go into quirks mode is an important tip, but equally useful is writing valid HTML 4. The reason is that the old IE browsers are much more likely to render the page the same as a modern browser if you ensure the HTML is valid. This is rather difficult to test if most of the HTML has been created using jQuery. Here is a piece of Javascript that takes the 'live' HTML from the page and submits it to the W3C validation service.

Using the code

Save the source code as html_validation.js and include in the HTML file in the usual way with 

<script src="html_validator.js" type="text/javascript"></script>

Source code

$( document ).ready(function() {<br />
    var html_validator_form = $('<form action="http://validator.w3.org/check" method="POST" style="border:none;background:none">' +<br />
                                '<div title="validate HTML">' +<br />
                                '<input type="hidden" name="fragment"></div></form>');<br />
    html_validator_form.appendTo($("body"));<br />
    html_validator_form.find("div")<br />
    .css({opacity: "0.33", cursor: "pointer", background: "green", border: "none", padding: "0px", margin: "0px"})<br />
    .width(20)<br />
    .height(20)<br />
    .offset({top:0,left:0})<br />
    .hover(<br />
      function() {<br />
        $( this ).css( "opacity", "0.5" );<br />
      }, function() {<br />
        $( this ).css( "opacity", "0.33" );<br />
      }<br />
    );<br />
    html_validator_form.click(function() {<br />
        $(this).remove();<br />
        var markup = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>\n' + <br />
          $("html").html() + <br />
          '\n</html>';<br />
        $(this).appendTo($("body"));<br />
        $(this).find("input").val(markup);<br />
        $(this).submit();<br />
    });   <br />
});

This will add a small green square in the top left corner of the web page. Click the square to see how the HTML validates.

Writing valid code will make things go easier when supporting legacy browsers. Of course you also have to keep that CSS to CSS 2, but that's another story.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)