1

I have the following ASP.net page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tks.aspx.cs" Inherits="Dr.Tks" ValidateRequest="true" %>

<asp:TextBox ID="tbComments" ClientIDMode="Static" CssClass="tbTech" runat="server" TextMode="MultiLine" Columns="30" Rows="15"></asp:TextBox>
<asp:Button ID="SubmitForm" ClientIDMode="Static" runat="server" Text="Submit" OnClick="ValidateForm" CssClass="btnFancy orange logBtn btnLogIn lightLinks" UseSubmitBehavior="false" />

C#:

public void ValidateForm(object sender, EventArgs e)
{
    try
    {
        string strTheBody = HttpUtility.HtmlEncode(tbComments.Text);
    }
    catch (Exception)
    {
    }
}

If I enter <script... in the textbox above, I get the following error:

Server Error in '/' Application.
--------------------------------------------------------------------------------
A potentially dangerous Request.Form value was detected from the client (tbComments="<script...").

How can I validate the textbox as I type, rather than display the default error message from ASP.net (which is not user friendly)

SearchForKnowledge
  • 3,663
  • 9
  • 49
  • 122

2 Answers2

1

In .NET 4.5 , you can set ValidateRequestMode="Disabled" on a control.

<asp:TextBox ID="tbComments" ValidateRequestMode="Disabled" ClientIDMode="Static" CssClass="tbTech" runat="server" TextMode="MultiLine" Columns="30" Rows="15"></asp:TextBox>
Angus Chung
  • 1,547
  • 1
  • 11
  • 13
0

There are several ways you can resolve this issue for better user experiences. You can use JavaScript, ASP.NET Validator, Disable Request validation Feature (not recommend - read this:Request Validation in ASP.NET - do it only when you want to allow markup otherwise there is a secuity issue), or use some other tools.

One of the ASP.NET validators could resolve your issue, and it is : RegularExpressionValidator. For detail please visit: Types of Validation for ASP.NET Server Controls

Please try this:

<asp:RegularExpressionValidator id="RegularExpressionValidator1"
ControlToValidate="tbComments"
ValidationExpression="^([A-Za-z]|[0-9]|_)+$"
Display="Static"
EnableClientScript="true"
ErrorMessage="Please enter valid string only"
runat="server"/>

This will happen on client side, just like javascript.

Deep
  • 1,025
  • 11
  • 7