XHTML won't validate && and < in a JavaScript function
Asked Answered
F

5

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.

Fairy answered 3/10, 2009 at 14:30 Comment(3)
You could replace your expression by this one: !(!(user_age > 15) || !(91 > user_age)). But that’s just a workaround.Isothere
Adding the CDATA tags fixed the issue. Thanks very much.Fairy
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 <xsl:value-of select="cdataNode" disable-output-escaping="yes"/>Milan
S
42

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> 
Sierra answered 3/10, 2009 at 14:33 Comment(1)
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.)Trueman
V
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.

Vilma answered 3/10, 2009 at 14:31 Comment(1)
css should also be in it's own fileGoldcrest
M
2

All Javascript should be CDATA in XHTML:

<![CDATA[
if (user_age > 15 && user_age < 91)
]]>
Montero answered 3/10, 2009 at 14:33 Comment(2)
Don't forget to comment it out as <![CDATA[]]> is an XML literal in JavaScript.Zumwalt
Internet Explorer seems to conflict with this. For example, errors out when there are &lt; symbols in Javascript code.Busterbustle
E
1

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

Emblaze answered 3/10, 2009 at 14:33 Comment(1)
As stated in a reply to Martin's answer: Don't forget to comment it out as <![CDATA[]]> is an XML literal in JavaScript.Zumwalt
C
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.

Chiasma answered 12/2, 2016 at 16:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.