Follow Up: Enable ValidateRequest in ASP.NET and still read HTML

Last week I read a great post on Mad’s Blog about Re-Enable Request Validation in ASP.NET. He built a javascript function which automatically HTMLEncodes the Text on Clientside when the User hits Submit by using Tagmapping and automatically HTMLDecodes it on server-side.

By using his technique you can still benefit of the ValidateRequest Security while allowing HTML in your forms.

Now to the Follow Up: If you use ASP:Panels on your webform and you hide specific Panels which do include Textboxes to show them just on specific events you run into a Javascript Error saying tb is null. That’s because the HTML Output which is dynamically created doesn’t contain the textbox when the Panel is hidden, although ASP.NET is executing the JS Statement for those hidden textboxes anyway and that’s when the Error pops up. You can fix that pretty easy by checking if tb is null, here’s Mad’s Code containing that little fix:

public class SafeTextBox : System.Web.UI.WebControls.TextBox
protected override void OnLoad(System.EventArgs e)
if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "TextBoxEncode"))
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("function TextBoxEncode(id)");
sb.Append("var tb = document.getElementById(id);");
sb.Append("if (tb != null){"); //fix
sb.Append("tb.value = tb.value.replace(new RegExp('<', 'g'), '<');");
sb.Append("tb.value = tb.value.replace(new RegExp('>', 'g'), '>');");
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "TextBoxEncode", sb.ToString(), true);

// Adds the function call after the form validation is called.
if (!Page.IsPostBack)
Page.Form.Attributes["onsubmit"] += "TextBoxEncode('" + ClientID + "');";

public override string Text
get { return base.Text; }
if (!string.IsNullOrEmpty(value))
base.Text = value.Replace("<", "<").Replace(">", ">");
base.Text = value;

Read Mad’s full article on how to implent this technique and be sure to turn ValidateRequest back on!


There are no comments yet...Kick things off by filling out the form below.

Leave a Comment