XHTML and code inside textareas

2019-06-21 18:41发布

On a site of mine in which a textarea is used for submission, I have code that can appear something along the lines of the following:

<textarea><p>text</p></textarea>

When validating (XHTML 1.0 Transitional), this error arises,

line 88 column 50 - Error: document type does not allow element "p" here

If this is not a valid method, then what is expected? I could do a workaround with an onload JavaScript event, but that seems needless. Regardless this doesn't affect the output, but I'd rather my site validate.

6条回答
姐就是有狂的资本
2楼-- · 2019-06-21 18:52

Would a CDATA section be an option for you?

<textarea><![CDATA[
    <p>Blah</p>
]]></textarea>
查看更多
欢心
3楼-- · 2019-06-21 19:00

is there a reason you're trying to put a <p> within <textarea>? as you found out it's not valid. if it's for display purposes (ie, showing code) it should be translated:

<textarea>&lt;p&gt;text&lt;/p&gt;</textarea>

beyond validation issues, allowing arbitrary tags (which are not properly encoded as above) to display can be a huge security issue. it's paramount to make sure any user supplied input has been properly sanitized before it is displayed.

查看更多
▲ chillily
4楼-- · 2019-06-21 19:00

Am I right in thinking your trying to make a WYSIWYG editor, such as TinyMCE? What most seem to do is use HTML entities in the textarea and convert it to HTML via JavaScript.

查看更多
女痞
5楼-- · 2019-06-21 19:08

you could use this function on the posted data

function clean_data($value) {
    if (get_magic_quotes_gpc()) { $value = stripslashes($value); }
    $value = addslashes(htmlentities(trim($value)));
    $value = str_replace("\'", "&#39;", $value);
    $value = str_replace("'", "&#39;", $value);
    $value = str_replace(":", "&#58;", $value);
    return $value;
}
查看更多
等我变得足够好
6楼-- · 2019-06-21 19:11

You can leave out the tags in the text area, and when you need new lines use \n Otherwise use &lt;p&gt; and &lt;/p&gt; in the place of your tags.

查看更多
虎瘦雄心在
7楼-- · 2019-06-21 19:11

You could use an onload function to replace starts and ends tags of the textarea content.

eg: replace < > with &lt; &gt;

<textarea cols="" rows="">&lt;p&gt;text&lt;/p&gt;</textarea>

<p>text</p>

查看更多
登录 后发表回答