ASP.NET CustomValidator not working

Paweł Adamczyk picture Paweł Adamczyk · Dec 17, 2012 · Viewed 10.9k times · Source

I have problem: I have a custom validator on my page which validates imieTextbox control. But it's not working. And I don't know why.

This method comes from register.aspx.cs file:

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:

    <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). All validators(requiredfield validators) works fine, but custom validators is not. Why is that? What am I doing wrong?

Answer

slfan picture slfan · Dec 17, 2012

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;
}