如何在表单中显示错误消息

时间:2015-04-13 20:26:57

标签: c# asp.net

我有以下ASP.net页面:

<%@ 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)
    {
    }
}

如果我在上面的文本框中输入<script...,我会收到以下错误:

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

如何在键入时验证文本框,而不是显示ASP.net的默认错误消息(用户不友好)

2 个答案:

答案 0 :(得分:1)

在.NET 4.5中,您可以在控件上设置 ValidateRequestMode =“已禁用”

<asp:TextBox ID="tbComments" ValidateRequestMode="Disabled" ClientIDMode="Static" CssClass="tbTech" runat="server" TextMode="MultiLine" Columns="30" Rows="15"></asp:TextBox>

答案 1 :(得分:0)

有几种方法可以解决此问题,以获得更好的用户体验。您可以使用JavaScript,ASP.NET验证程序,禁用请求验证功能(不推荐 - 请阅读:Request Validation in ASP.NET - 仅在想要允许标记时执行此操作否则有安全问题),或使用其他一些工具。

其中一个ASP.NET验证程序可以解决您的问题,它是: RegularExpressionValidator 。有关详细信息,请访问:Types of Validation for ASP.NET Server Controls

请试试这个:

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

这将在客户端发生,就像javascript一样。

相关问题