views:

339

answers:

4

Does asp.net have a built in mechanism that can sanitize all textbox input instead of redirecting to the error page?

I have a textbox input where a user can enter a name, but if they try to enter and <> tags the page automatically throws an error. I just want to handle this error in a user friendly way.

A: 

ASP.net has validation controls

[http://msdn.microsoft.com/en-us/library/7kh55542.aspx%5D%5B1%5D

Also there is Mark Down Editor which is a control that strips out html tags etc.

Gratzy
+1  A: 

You'll want to look at the AntiXSS library for that. It's a dll so it's easy to drop in and start using it.

The download is at CodePlex.

Gavin Miller
+1  A: 

You can use the ASP.NET RegularExpressionValidator control with a pattern like: ^[^<>]*$

<asp:RegularExpressionValidator ID="rev" runat="server"
    ControlToValidate="txtBox"
    ErrorMessage="The <> tags are not allowed!"
    ValidationExpression="[^<>]*" />
<asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="txtBox" 
    ErrorMessage="Value can't be empty" />

The RequiredFieldValidator is used in conjunction with the RegularExpressionValidator to prevent blank entries. If that textbox is optional, and only needs to be validated when something is entered, then you don't have to use the RequiredFieldValidator.

The benefit of doing it this way is that the error can be handled gracefully and the user can be notified on the same page.

However, if you need to do this for many textboxes and you just want to present something nicer than the error page, you could handle the ValidateRequest error to provide a friendlier message and keep the user on the same page (not just replace it with a custom error page). For more info, check out Kirk Evans' post: Handling ValidateRequest errors within a Page (refer to the section titled Overriding the OnError Method).

Ahmad Mageed