Click here to Skip to main content
Click here to Skip to main content

HTML validation for dynamic pages

, 6 Jul 2014
Rate this:
Please Sign up or sign in to vote.
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() {

    var html_validator_form = $('<form action="http://validator.w3.org/check" method="POST" style="border:none;background:none">' +

                                '<div title="validate HTML">' +

                                '<input type="hidden" name="fragment"></div></form>');

    html_validator_form.appendTo($("body"));

    html_validator_form.find("div")

    .css({opacity: "0.33", cursor: "pointer", background: "green", border: "none", padding: "0px", margin: "0px"})

    .width(20)

    .height(20)

    .offset({top:0,left:0})

    .hover(

      function() {

        $( this ).css( "opacity", "0.5" );

      }, function() {

        $( this ).css( "opacity", "0.33" );

      }

    );

    html_validator_form.click(function() {

        $(this).remove();

        var markup = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>\n' + 

          $("html").html() + 

          '\n</html>';

        $(this).appendTo($("body"));

        $(this).find("input").val(markup);

        $(this).submit();

    });   

});

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)

About the Author

CJ Hilder
Software Developer (Senior) BPAC Inc
New Zealand New Zealand
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 6 Jul 2014
Article Copyright 2014 by CJ Hilder
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid