3

我有问题:我的页面上有一个自定义验证器,用于验证 imieTextbox 控件。但它不起作用。我不知道为什么。

此方法来自 register.aspx.cs 文件:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
//of course here will be other validation logic but setting IsValid property ti false     is for example
        args.IsValid = false;
    }

这来自register.aspx 文件:

    <asp:CustomValidator ID="CustomValidator1" runat="server" 
             ControlToValidate="imieTextbox" Display="Dynamic" 
             ErrorMessage="CustomValidator" 
             onservervalidate="CustomValidator1_ServerValidate" ValidateEmptyText="True" 
             ValidationGroup="A"></asp:CustomValidator>

页面上的提交按钮将属性 CausesValidation 设置为 TRUE 并具有验证组 A(就像我页面上的所有验证器一样)。所有验证器(必填验证器)都可以正常工作,但自定义验证器不行。这是为什么?我究竟做错了什么?

4

1 回答 1

7

You have to call

if (Page.IsValid) 

on postback on the server, otherwise your server validation will not be called. The RequiredFieldValidator validates on the client, that's why this one is working. However you should always validate on the server as well.

For client side validation you have to write a JavaScript method doing the same. You set the attribute in your CustomValidator:

ClientValidationFunction="YourValidationMethod"

and the method does something like this

function YourValidationMethod(source, args)
{
   if (valid) // do check here
      args.IsValid = true;
   else
      args.IsValid = false;
}
于 2012-12-17T21:30:58.463 回答