-6

How do I check if what was written in the textarea by the user is valid HTML? It could be with either PHP or Javascript.

user3204179
  • 69
  • 2
  • 2
  • 9

3 Answers3

0

In php, it would be quite simple:

if($text!=htmlspecialchars($text))
{
    echo 'This contains HTML tags!!';
}

Of course, this means an ampersand would be valid, so you could also do something like

function hasHtml($string) {
    if ( $string != strip_tags($string) )
        return true;
}

You can use John Resig's html parser for the Javascript solution, or do something like this:

function is_html(string)
{
  return string.match("/<[^<]+>/").length != 0;
}
Cilan
  • 13,101
  • 3
  • 34
  • 51
0

You could post the contents to a html validation script or online service and show the result.

You may also want to investigate the PHP DOMDocument class which has some validating functionality.

flauntster
  • 2,008
  • 13
  • 20
0

in js, it's easy since it has an HTML parser built-in:

function isHTML(str){
  var div=document.createElement("div");
  div.innerHTML=str;
  return div.children.length>0;
}

note that this will validate that there is some well-formed html, or html that quirks into well-formed html. strict validity is another matter, and only FireFox lets you ajax view-source: urls to sniff for error title attribs in the gecko html display markup. Other browsers will need a server-side proxy to the w3 validator, or a on-site html validation service provided by your own server.

dandavis
  • 16,370
  • 5
  • 40
  • 36