HTML and CSS   XSLT   JavaScript   Images   Soft   Etc  
Vladimir Tokmakov

XML validation 13 December 2003


Task:

Check whether a string is a valid XML.

01 
02 
03 
04 
05 
06 
07 
08 
09 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
<script type="text/javascript">
    function xmlValidate( sValue ){
        if( sValue ){
            // cut command
            sValue = sValue.replace( /<\?.*\?>/g, '' );
            // cut doctype
            sValue = sValue.replace( /<\!DOCTYPE.*?>/g, '' );
            // cut comments and CDATA
            var rTags = /(<!--.*?-->|<\!\[CDATA\[.*?\]\]>)/g;
            while( sValue.search( rTags ) >= 0 ){
                sValue = sValue.replace( rTags, '' );
            }
            // cut single quoted strings
            sValue = sValue.replace( /<\w[-\w:]*(\s+[-\w:]+\s*=\s*(["'])[^<>]*?\2)*\s*\/>([^<]*)/gi, '' );
            // cut double quoted strings
            var rTags = /<(\w[-\w:]*(\s+[-\w:]+\s*=\s*(["'])[^<>]*?\3)*\s*>[^<>]*?<\/\1>([^<]*)/g;
            while( sValue.search( rTags ) >= 0 ){
                sValue = sValue.replace( rTags, '' );
            }
            if( sValue.search( /[<>]/ ) >= 0 || sValue.search( /&(?!(\w+;|#\d+;))/ ) >= 0 ){
                //alert( sValue )// may display sValue;
                return false;
            }
            return true;
        }else{
            return true;
        }
    }
</script>
<form name="example" onsubmit="return false">
    <textarea name="text" style="width: 100%; height: 10em;"></textarea>
    <input type="button" value="Validate"
        onclick="if( xmlValidate( document.example.text.value ) )
        { alert( 'It's OK!' ) }else{ alert( 'Not an XML!' ); }" />
</form>

Order a design...