15

Here's the snippet of code that won't validate:

if (user_age > 15 && user_age < 91)

It gets the following errors:

XML Parsing Error: StartTag: invalid element name

and

XML Parsing Error: xmlParseEntityRef: no name

The first error is thrown for the "less than" and the second one is thrown twice, once for each ampersand.

Replacing the above signs with & and < validates fine, but of course it completely ruins the function.

  • You could replace your expression by this one: `!(!(user_age > 15) || !(91 > user_age))`. But that’s just a workaround. – Gumbo Oct 03 '09 at 14:34
  • Adding the CDATA tags fixed the issue. Thanks very much. –  Oct 03 '09 at 14:36
  • PROBLEM IF Javascript was into a XML and XHTML is generated by XSLT: the CDATA ">", "<" and "&" are converted. alert((2>1)? 'OK1': 'OK2'); // is converted! Use – Peter Krauss Sep 19 '11 at 10:27

5 Answers5

40

Or you can protect the script from the xml validation like this:

<script type="text/javascript"> 
//<![CDATA[
    if (user_age > 15 && user_age < 91) {
        // do soemthing
    }
//]]>
</script> 
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 2
    protect from xml validation, that sounds like cheating in a test. Literal &<> must be inside CDATA in valid XML, without it, Firefox should refuse rendering the document if Firefox were conformant (but now the document is probably not served as `application/xhtml+xml` so it won't happen.) – u0b34a0f6ae Oct 03 '09 at 14:41
8

Move script to other file :)

It is standard (and good) habit to separate style (into .css file), data (.html) and of course scripts to .js file.

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
2

All Javascript should be CDATA in XHTML:

<![CDATA[
if (user_age > 15 && user_age < 91)
]]>
Martin
  • 11,031
  • 8
  • 50
  • 77
1

put javascript in <![CDATA[...]]> section

Xinus
  • 29,617
  • 32
  • 119
  • 165
  • 2
    As stated in a reply to Martin's answer: Don't forget to comment it out as <![CDATA[]]> is an XML literal in JavaScript. – Eli Grey Oct 03 '09 at 20:40
0

you can try CDATA but some time it wont work, it depends on the setting of the server I guess. I am not a pro, but i tested, and I did not work, but if you put the javascript code in the .js file and then link this file somewhere in your body. it will definitely work. PERSONALLY TESTED.