New Technologies

  • Java
  • Javascript
  • DTML
  • Dot Net
  • ASP .Net
  • C# .Net
  • PHP
Your Ad Here

Sunday, February 24, 2008

XSD validation in Javascript

var sOutput = validateFile("sc-valid.xml");

function validateFile(strFile)
// Create a schema cache and add books.xsd to it.
var xs = new ActiveXObject("MSXML2.XMLSchemaCache.4.0");
xs.add("urn:books", "sc.xsd");

// Create an XML DOMDocument object.
var xd = new ActiveXObject("MSXML2.DOMDocument.4.0");

// Assign the schema cache to the DOMDocument's
// schemas collection.
xd.schemas = xs;

// Load books.xml as the DOM document.
xd.async = false;
xd.validateOnParse = true;
xd.resolveExternals = true;

// Return validation results in message to the user.
if (xd.parseError.errorCode != 0)
return("Validation failed on " + strFile +
"\n=====================" +
"\nReason: " + xd.parseError.reason +
"\nSource: " + xd.parseError.srcText +
"\nLine: " + xd.parseError.line + "\n");
return("Validation succeeded for " + strFile +
"\n======================\n" +
xd.xml + "\n");


File: sc-valid.xml
<?xml version="1.0"?>
<x:catalog xmlns:x="urn:books">
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<description>An in-depth look at creating applications
with XML.</description>

File: sc.xsd
<xsd:schema xmlns:xsd=""
<xsd:element name="catalog" type="b:CatalogData"/>
<xsd:complexType name="CatalogData">
<xsd:element name="book"
<xsd:complexType name="bookdata">
<xsd:element name="author" type="xsd:string"/>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="genre" type="xsd:string"/>
<xsd:element name="price" type="xsd:float"/>
<xsd:element name="publish_date" type="xsd:date"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:attribute name="id" type="xsd:string"/>

1 comment:

andy said...

Like your article :)

Any chance of using that XSD file to contain language locaization.

What I mean is, quite a few javascripts have hard coded messages, so we control can can fix, some we cannot due to design or due to ownership.

given his kind of response
"you have 43 messages"

It would be great if that message could be auto converted using a scheme that contains language oriented content such as
"jij heb 43 berichten" (dutch version) obviously keeping the int intact when changing.

Your Ad Here