PDA

View Full Version : xHTML validator in Javascript


drewamnh
07-23-2003, 07:19 PM
I wrote this simple tag validator - anyone have suggestions to make it more robust?

<html>
<head>
<script language="javascript">

function checkTags(){

var htmlText=document.validateForm.html.value;
var tagtext = new Array();
var addme = false;
var opentags = new Array();
var htmlOK = true;

for(i=0;i<htmlText.length;i++){
tLetter = htmlText.substring(i,i+1);
if (tLetter=='>'){
addme=false;
tag=tagtext.join("");
if (tag.indexOf('/')>=0){
//alert (tag);
//alert (tag.indexOf(opentags[opentags.length-1]));

if (tag.indexOf(opentags[opentags.length-1])>=0){
opentags.length = opentags.length-1;
}
else {
if (tag.indexOf('br')>=0){
//ignore! these br tags are cool!
}
else{
htmlOK = false;
}
}
}
else{
if (tag.indexOf('br')>=0){
htmlOK = false; // br tag must be written correctly!
}
else{
opentags[opentags.length] = tag;
}
}
tagtext = new Array();
}
if (addme==true){
tagtext[tagtext.length] = htmlText.substring(i,i+1);
}
if (tLetter=='<'){
addme=true;
}
}

if (htmlOK==false || opentags.length > 0){
alert ("your xHTML is crap!");
}
else{
alert ("Good job, your xHTML is great!");
}

}

</script>
</head>
<body >
<table width="100%" border="0" cellpadding="10" align="left"><tr><td>
<form name="validateForm" >
<textarea cols="60" rows="10" name="html">test <p><b><i></i></b></p></textarea><br>
<input type="button" name="validate" value="Validate HTML" onClick="checkTags();">
</form>
</td></tr></table>
</form>
</body>
</html>

beetle
07-23-2003, 07:59 PM
Calling this an "XHTML Validator" is certainly stretching the term.

Basically - you are just testing for improper nesting, which is cool, but not by a long shot does that mean you are validating XHTML. XHTML has many requirements to be valid. Some would be easy to check with javascript, but many would not be easy.

It's cool, but it's no XHTML validator by my book.

Besides, there are more self-closing tags other than <br/>

<img/>
<link/>
<base/>
<area/>
<hr/>
<meta/>
<input/>

You can read some here (http://www.htmlgoodies.com/tutors/xhtml.html#rules) about other requirements of XHTML.

Of course, having said all that, I'm really curious as to why you wish to make a javascript-driven validator, when the W3C's (http://validator.w3.org/) works perfectly fine?