简体   繁体   English

ASP.NET CustomValidator无法正常工作

[英]ASP.NET CustomValidator not working

I have problem: I have a custom validator on my page which validates imieTextbox control. 我有问题:我的页面上有一个自定义验证器,用于验证imieTextbox控件。 But it's not working. 但它不起作用。 And I don't know why. 我不知道为什么。

This method comes from register.aspx.cs file: 这个方法来自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;
    }

And this comes fromregister.aspx file: 这来自fromregister.aspx文件:

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

Submit button on Page has property CausesValidation set to TRUE and has Validation group A (like all validators on my page). 页面上的提交按钮具有属性CausesValidation设置为TRUE并具有验证组A(与我页面上的所有验证器一样)。 All validators(requiredfield validators) works fine, but custom validators is not. 所有验证器(requiredfield验证器)工作正常,但自定义验证器不工作。 Why is that? 这是为什么? What am I doing wrong? 我究竟做错了什么?

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. RequiredFieldValidator在客户端上验证,这就是为什么这个工作正常。 However you should always validate on the server as well. 但是,您应该始终在服务器上进行验证。

For client side validation you have to write a JavaScript method doing the same. 对于客户端验证,您必须编写一个JavaScript方法。 You set the attribute in your CustomValidator: 您在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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM