Search code examples
coldfusionhtml-entitiescoldfusion-8

How can I prevent ColdFusion from converting HTML Entity?


Let's assume I have data store that I cannot change.

Within that data store I have a table of string values:

  • BROWN
  • BLUE & RED
  • YELLOW & PURPLE
  • BLACK

Note that the values can contain both HTML entities and their coutnerparts (i.e. & and &).

Now, I want to output those values as input values (checkboxes).

With no manipulation, ColdFusion converts the & to &. When that checkbox is selected and I validate it against the data store, it fails, since YELLOW & PURPLE (data store value) does not equal YELLOW & PURPLE (form value).

Here is the current [pseudo] code I'm using to output the checkboxes:

<cfquery name="LOCAL.qColors">
    SELECT
        COLOR
    FROM    COLORS
</cfquery>

<cfoutput query="LOCAL.qColors">
    <div>
    <input
        id="color-#CURRENTROW#"
        type="checkbox"
        class="checkbox"
        name="colors"
        value="#COLOR#"
        #IIF(ListFindNoCase(FORM.colors, COLOR), "'checked'", "")# />
    <label for="color-#CURRENTROW#">
        #COLOR#
    </label>
    </div>
</cfoutput>

How can I prevent ColdFusion from decoding the HTML entity and just using the exact string I want?


Solution

  • Chances are, it has nothing to do with ColdFusion and it's actually your browser (correctly) interpreting HTML entities in the HTML source of your page. If you have any string which you do NOT want your browser to parse as HTML, then you must escape it. Use the HTMLEditFormat() function when outputting the value.

    This might be especially important if your values ever contain a double quote. And as a general precaution, NEVER output naked (unescaped) text into your webpage that you don't expect to have safe parseable HTML in it for both display issues as well as security concerns.

    ColdFusion 9 and lower

    #HTMLEditFormat( arbitraryValue )# 
    <input name="myOptions" type="checkbox" value="#HTMLEditFormat( arbitraryValue )#">

    ColdFusion 10+

    #encodeForHTML( arbitraryValue )# 
    <input name="myOptions" type="checkbox" value="#encodeForHTMLAttribute( arbitraryValue )#">

    You will then see in the HTML source of the page that "BLUE & RED" becomes "BLUE &amp; RED" and "YELLOW &amp; PURPLE" becomes "YELLOW &amp;amp; PURPLE". When that HTML is parsed, the original value will be used and submitted by the form.