2

If I have a text area that can display user entered input. How should I encode it to prevent any security issues?

For instance suppose I have this:

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
    <form>
        <textarea></textarea><script>alert('Hello');</script></textarea>
    </form>
</body>
</html>

How should I encode the contents of the textarea so that it shows the </textarea><script> as text rather than running it?

I'm using ASP.Net, but I'm really after a general answer for HTML.

This is different to "Rendering HTML inside textarea" as I don't want to render HTML inside the textarea where as with that question they did.

Martin Brown
  • 23,657
  • 13
  • 76
  • 113

2 Answers2

2

You use HTMLEncode.

<textarea><%= Server.HtmlEncode("</textarea><script>alert('Hello');</script>") %></textarea>

Or

TextBox1.Text = Server.HtmlEncode(myString);
VDWWD
  • 33,993
  • 20
  • 58
  • 76
0

If you want to post <script>the tag will be picked up.
Displaying a tag as text type &lt; and &gt; they will be displayed as < > Link

So the html would look like:

<textarea> &lt;/textarea&gt; &lt;script&gt;alert('Hello');&lt;/script&gt; </textarea>

but @VDWWD answer is a better solution for asp.net development.

Persijn
  • 14,184
  • 3
  • 41
  • 72