Reputation: 3675
I have a textbox in my aspx page. The user wants to have the ability to input html tags in the textbox. The only way so far I know to by pass the validation error is set the ValidateRequest to false. I tried couple of other ways: (1) using Server.HtmlEncode in a javascript like this
<%@ Import Namespace="System.Web" %>
var tb = document.getElementById("<%=synopsisTextBox.ClientID%>");
var value =Server.HtmlEncode(tb.value);
But I got compiler error. Can anyone tell me what I did wrong?
(2) creating my own encode function
function escapeHTML (str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
somehow it didn't work quite well. When I click some button that causes postback in the same page, it gets stuck.
Can anyone tell me if there is a better way to make your textbox accept html tags? Thanks.
Upvotes: 1
Views: 11506
Reputation: 7941
IMO, you have these following solutions:
Upvotes: 0
Reputation: 12721
If you need to encode html tags and show them on a browser remember that
<%= Server.HTMLEncode("The paragraph tag: <P>") %>
produces the following output:
The paragraph tag: <P>
that will be displayed by a Web browser as:
The paragraph tag: <P>
Your trial with Server.HTMLEncode is not working, since it works when data are on the server and need to be encoded before sending to the browses. In your sample, data are on the browser and request is blocked on validation before being recieved on the server .
If you want user to edit TextBox and enter html tags you can disable this via
<%@ Page validateRequest="false" ...>
or in the web.config for your entire application:
<system.web>
<page validateRequest="false" />
</system.web>
Note that this ValidateRequest property is not existing without reason. When you change its default value, insecure input will be accepted. Because of that, you need to validate every user's input to avoid cross-site scripting attacks, like inserting of malicious JavaScript, ActiveX, Flash or HTML
Another smart solution is to replace via javascript text written by user to make it safe for validation.
< tag>
, instead of <tag>
is considered safe!
function validateTxt() {
$("textarea, input[type='text']").change(function () {
html = $(this).val(); //get the value
//.replace("a" , "b") works only on first occurrence of "a"
html = html.replace(/< /g, "<"); //before: if there's space after < remove
html = html.replace(/</g, "< "); // add space after <
$(this).val(html); //set new value
});
}
$(document).ready(function () {
validateTxt();
});
Upvotes: 1
Reputation: 23561
Just disable input validation (for the page only) and make sure you encode input from other textboxes in the page. Input validation is on by default not because it shouldn't be disabled ever but because you should know what you are doing and do it explicitly. This way you are sure to pay attention and do your own input validation.
Upvotes: 5