February 25, 2002 - Validating DOMDocument Upon Request | WebReference

February 25, 2002 - Validating DOMDocument Upon Request

Yehuda Shiran February 25, 2002
Validating DOMDocument Upon Request
Tips: February 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

Since you can add and modify nodes to the DOMDocument tree, there must be a way to validate the DOMDocument upon request, and not only upon loading. You can do this in later versions of Internet Explorer with the validate() method. Here is code that loads an XML file, adds an attribute to the root node, and validates the new DOMDocument:

function validateXML() {
  var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
  xmlDoc.async = false;
  xmlDoc.load("mydvd7.xml");
  xmlDoc.documentElement.setAttribute("foo", "bar");
  var err = xmlDoc.validate();
  if (err.errorCode == 0) {
    alert("Document is valid");
  } else {
      alert("Validation error:" + err.reason);
	}
}
Notice the err error object that holds very useful information. For example, it pinpoints the fact that the new attribute "foo" is not defined in the DTD file and hence is illegal. Try it.