ASP.NET自定义验证程序无法正常工作

时间:2016-01-23 23:13:38

标签: c# asp.net customvalidator

我已完成了this page告诉我要做的所有事情,但它没有工作,我发现人们发布了有关此问题并被告知要添加必填字段验证器,我已经做到了,仍然无法正常工作。

这是客户端部分

                <asp:CustomValidator 
                    ID="CustomValidator1" 
                    runat="server" 
                    ControlToValidate="TextBoxUsername" 
                    ErrorMessage="Username already exists" 
                    OnServerValidate="CustomValidator1_ServerValidate" 
                    ValidateEmptyText="True" <!--tried without this line-->
                    ValidationGroup="form">  <!--tried without this line-->
                </asp:CustomValidator>

这是C#服务器端代码

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){
            args.IsValid = false;
        }

看起来很简单吧?它应该一直出现,对吧? 好吧,它只出现在开头,然后永远消失,因为我在page_load()方法中有这一行,但我也在button_click()方法中有它。

Page.Validate();

1 个答案:

答案 0 :(得分:2)

首先,删除验证组,然后添加Text

<asp:CustomValidator 
    ID="CustomValidator1" 
    runat="server" 
    ControlToValidate="TextBoxUsername" 
    ErrorMessage="Username already exists" 
    Text="Username already exists"
    OnServerValidate="CustomValidator1_ServerValidate" 
    ValidateEmptyText="True">
</asp:CustomValidator>

ErrorMessage将显示在ValidationSummary控件中,Text应显示验证程序的位置。

更新按钮以进行验证(我认为无论如何都是默认值,但让我们明确):

然后点击后检查页面是否有效,Page.Validate不需要被调用,因为CauseValidation会自动调用该页面。

protected void Button1_Click(object sender, EventArgs e)
{ 
   if (Page.IsValid)
   {
       // Do Cool Stuff
   }
}

此外,在检查时忽略click方法,因为您没有任何客户端连接(例如验证器上的ClientValidationFunction="somejsfunction"),因此当您到达服务器端时,您只会点击此代码验证

相关问题