12

In html does the text inside the img tag's alt attribute require encoding/escaping?

Non encoded example:

<img src="myimg.png" alt="image description" />

Encoded example:

<img src="myimg.png" alt="image%20description" />
Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
stukelly
  • 4,257
  • 3
  • 37
  • 44

4 Answers4

21

No, it does not need to be encoded like a URI. However, HTML characters must be encoded, like this...

<img src="myimg.png" alt="Me &amp; my image" />
JohnFx
  • 34,542
  • 18
  • 104
  • 162
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
  • Replace "should" with "must" -- at least if you want to pass a validator – kdgregory Jul 22 '09 at 14:26
  • 4
    Replace with must if you don't want be caught out putting quotes in there. – Matthew Scharley Jul 22 '09 at 14:27
  • Replace with must if you don't want the yellow screen of death (assuming you are serving your XHTML as application/xhtml+xml, othewise writing XHTML is just more trouble then it is worth) – Quentin Jul 22 '09 at 14:30
  • You're right guys. Sorry about that. Although with HTML5 on the horizon, I am still not sure how important it is. – Josh Stodola Jul 22 '09 at 14:37
5

They do not require URL encoding, but they do require, as all XHTML attributes do, XHTML entity encoding.

Incorrect:

<img src="foo.gif" alt="Ben & Jerry's" />

Correct:

<img src="foo.gif" alt="Ben &amp; Jerry's" />

You would also need to encode double-quotes within the values, even though you don't have to do that in general text.

Reference:

richardtallent
  • 34,724
  • 14
  • 83
  • 123
2

No it does not. Encoding is for URLs as in http://en.wikipedia.org/wiki/Dream%20Theater, which the alt string is not.

You will need to use entity-encoding to escape > as &gt;, and " as &quot;, though. Note that that is different from URI encoding where special characters are encoded as a percent sign plus two hex digits.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
-1

You should use HTML encoding (i.e. " becomes "), not URL encoding. If you are using ASP.NET you can achieve this with Server.HtmlEncode or better yet use the HtmlAttributeEncode method in the AntiXSS Library on CodePlex.

Colin Bowern
  • 2,152
  • 1
  • 20
  • 35