9

I have the following piece of asp:

<asp:ValidationSummary ID="RegisterUserValidationSummary" runat="server" CssClass="failureNotification" 
        ValidationGroup="RegisterUserValidationGroup"/>

...

<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserNameTB">Username:</asp:Label>
<asp:TextBox ID="UserNameTB" runat="server" CssClass="textEntry"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="UserNameTB" 
      ValidationExpression="[a-zA-Z]{3,8}" ErrorMessage="Username must be between 3 to 8 chars" runat="server"
      CssClass="failureNotification" ToolTip="Username must be between 3 to 8 chars" ValidationGroup="RegisterUserValidationGroup">
    *</asp:RegularExpressionValidator>
<asp:CustomValidator ID="NoUserValidator" ControlToValidate="UsernameTB" runat="server" ErrorMessage="User Taken!" CssClass="failureNotification" 
      ValidationGroup="RegisterUserValidationGroup"  OnServerValidate="UserValidate">*</asp:CustomValidator>

And then the function:

protected void UserValidate(object source, ServerValidateEventArgs args)
    {
        SqlDataSource1.SelectCommand = "SELECT ClientID FROM [Clients] WHERE Username= '" + UserNameTB.Text + "'";
        DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
        if (dv.Table.Rows.Count != 0)
            args.IsValid = false;
        else
            args.IsValid = true;
    }

Button:

<asp:Button ID="CreateUserButton" runat="server" CommandName="MoveNext" Text="Create User" 
       ValidationGroup="RegisterUserValidationGroup" 
       onclick="CreateUserButton_Click"/>

Problem is that even though the custom validator function is called and sets .IsValid to false, the button logic still runs!

shA.t
  • 16,580
  • 5
  • 54
  • 111
RanH
  • 740
  • 1
  • 11
  • 31

1 Answers1

11

In your onclick function for the button, add a check to see if the page is valid

protected void CreateUserButton_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    { 
        // Create the user
    }
}

That should do it. This is because your custom validator is set up to validate on the server, during the postback. What happens is that the code first runs the validator code UserValidate, where you set the IsValid flag. Next in the postback stack is the button's onclick function. This function will run regardless of the result in the validator function, so this is where you need to check the value of the IsValid flag. This is the behavior when you validate the custom validation control on the server side.

An alternative is to validate on the client side. If you look at the page source code generated by your browser, you'll see that Javascript is added for the RegularExpressionValidator. It's behavior is known, and handled on the client side, so no post back is required to evaluate the expression and validate the page (it's all handled by javascript). The custom validator function is not known, so a postback is required unless you define a client-side validation script yourself.

Here's a link to more information on MSDN.

The Jonas Persson
  • 1,726
  • 1
  • 17
  • 36
  • 1
    Thanks it fixed it, can you explain why it works fine with the other validators, and for the custom one i had to add what you wrote ? – RanH Jun 16 '12 at 15:46
  • 1
    Actually, I'm not sure, so I'm just going to guess, but I think it's because the other validators are validating on the client side, while the custom validator is validating server side. Since it's server side, the postback has already begun, and you are first executing your custom validator, then the button's click function. Does that make sense? – The Jonas Persson Jun 16 '12 at 15:50
  • The way you describe it makes sense, but I would expect the page to wait for all validators approval before continuing, and besides all of the others are also configured to runat= server, but maybe that doesn't matter on them? – RanH Jun 16 '12 at 15:56
  • 3
    That they are set to runat=server only means that the server generated them, and that you can access them in the code-behind. But, if you look at the page source code generated by your browser, you'll see that javascripts are added for the regularexpressionvalidator. It's behavior is known, so no post back is required to evaluate the expression and validate the page (it's all handled by javascript). The custom validator function is not known, so a postback is required (unless you set up a clientside validation script in javascript). – The Jonas Persson Jun 16 '12 at 16:03
  • 1
    Thanks. This really helped me. By any chance do you have a `MSDN` reference for it? Or any other article/blog reference? – LCJ Dec 12 '12 at 12:35
  • 1
    This link describes it fairly well [http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator(v=vs.80).aspx](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator(v=vs.80).aspx) – The Jonas Persson Dec 12 '12 at 21:06