Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET CustomValidator not working

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?

like image 632
Paweł Adamczyk Avatar asked Apr 19 '26 22:04

Paweł Adamczyk


1 Answers

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;
}
like image 68
slfan Avatar answered Apr 21 '26 13:04

slfan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!