What values can I put in an HTML attribute value?

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

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

Is this valid?

Hi 

回答1:

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 " and & respectively (or the equivalent numeric entity references, " and &)

You can also use single quotes around an attribute value. If you do this, you may use literal double quotes within the attribute: .... In order to escape single quotes within such an attribute value, you must use the numeric entity reference ' since some browsers don't support the named entity, ' (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.



回答2:

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

Hi 


回答3:

The value can be anything, but you should escape quotes (", '), tag delimiters (<, >) and ampersands (&).



回答4:

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



回答5:

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

Hi 

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

Hi 


回答6:

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: \' " =  ` &.'; }, 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!