Kyle
Kyle

Reputation: 22055

What values can I put in an HTML attribute value?

Do I need to escape quotes inside of an html attribute value? What characters are allowed?

Is this valid?

<span title="This is a 'good' title.">Hi</span>

Upvotes: 31

Views: 24128

Answers (6)

Brian Campbell
Brian Campbell

Reputation: 333266

If your attribute value is quoted (starts and ends with double quotes "), then any characters except for double quotes and ampersands are allowed, which must be quoted as &quot; and &amp; respectively (or the equivalent numeric entity references, &#34; and &#38;)

You can also use single quotes around an attribute value. If you do this, you may use literal double quotes within the attribute: <span title='This is a "good" title.'>...</span>. In order to escape single quotes within such an attribute value, you must use the numeric entity reference &#39; since some browsers don't support the named entity, &apos; (which was not defined in HTML 4.01).

Furthermore, you can also create attributes with no quotes, but that restricts the set of characters you can have within it much further, disallowing the use of spaces, =, ', ", <, >, ` in the attribute.

See the HTML5 spec for more details.

Upvotes: 48

What Would Be Cool
What Would Be Cool

Reputation: 6818

Here is a validation function using a Regular expression based on Brian Campbell's answer, for worst case of an unquoted attribute.

validator: function (val) {
  if (!val || val.search(/['"=<>`]+|(&\s)+/) === -1) return true;
    return 'Disallowed characters in HTML attributes: \' " = < > ` &.';
},

Upvotes: 0

Emmanuel
Emmanuel

Reputation: 5403

Yes that's fine. The problem would be when you try and put a double Quote inside an attribute. like this:

<span title="This is a "bad" title.">Hi</span>

You can get around this by using HTML entities like so:

<span title="This is a &quot;good&quot; title">Hi</span>

Upvotes: 1

Adam Ayres
Adam Ayres

Reputation: 8910

No, you do not need to escape single quotes inside of double quotes.

This page specifies valid attributes of a span tag:

http://www.w3.org/TR/html401/struct/global.html#edef-SPAN

This page specifies valid characters allowed in the title attribute:

http://www.w3.org/TR/html401/intro/sgmltut.html#attributes

Upvotes: 3

Peter Olson
Peter Olson

Reputation: 143037

That is valid. However, if you had to put double quotes inside, you would have to escape with &quot; like this:

<span title="This is a &quot;good&quot; title.">Hi</span>

Upvotes: 4

casablanca
casablanca

Reputation: 70731

The value can be anything, but you should escape quotes (&quot;, &apos;), tag delimiters (&lt;, &gt;) and ampersands (&amp;).

Upvotes: 3

Related Questions