2

Writing a custom validator for a dropdownlist that is using autopostback. Seems to ignore the validation altogether. Why is it ignored and is there an easy fix?

Note I did not use ControlToValidate

asp.net:

     <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional" Visible="true" RenderMode="Inline">
        <ContentTemplate>
        <asp:DropDownList ID="ddlCommandAssign" runat="server" AutoPostBack="true">
        </asp:DropDownList>
          <asp:CustomValidator id="val_command_assigned" runat="server"  
          ErrorMessage="* " 
          display="Static"
          OnServerValidate="commandAssigned" 
          />
                </ContentTemplate>
       <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddlCommandAssign" 
                EventName="SelectedIndexChanged" />
        </Triggers>

    </asp:UpdatePanel>

Behind Code:

Sub commandAssigned(ByVal source As Object, _
  ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)

    Dim s As String
    s = ddlCommandAssign.SelectedValue
    'if s = "1" then 
    '  args.IsValid = true
    'else
    '  args.IsValid = False
    'end if
    args.IsValid = False
End Sub

For debugging purposes, I want it to fail every time.

It doesn't seem to be executing the behind code at all.

For debugging, I added the line response.redirect("dummy.html") ... which never gets called, which also indicates (I think) that the validator never gets called.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
elbillaf
  • 1,952
  • 10
  • 37
  • 73
  • I also added ValidateEmptyText="true" to the validator. Still no luck. – elbillaf Jun 30 '11 at 13:41
  • Is it important for you to have it validate through a postback? Are you opposed to doing it on the client side? Also, is there a reason you're not using the ControlToValidate. I noted that you didn't, like you said, but I'm not sure why. – Precious Roy Jun 30 '11 at 13:41
  • I'm changing the dropdownlist based on the value the user selects first. (I *hate* this, but the users are accustomed to the way the old system works.) I think I need to use the autopostback to update the ddl after I change it. I tried with and without controltovalidate. I tried without based on info I read on half-dozen sites. (No idea how reliable the advice is, but I generally assume the guy who got it to work knows something I don't.) – elbillaf Jun 30 '11 at 13:55

3 Answers3

2

Remove the update panel and try to do the validation at client-side itself using javascript.

CLIENT-SIDE VALIDATION

JavaScript event definition,

 function ValidateFunction(sender,args) 
 {
   var ddlCommandAssign= document.getElementById('<%=ddlCommandAssign.ClientID %>');
    if (ddlCommandAssign.options[control.selectedIndex].value=='0') 
    {  args.IsValid = false;//This shows the validation error message and stops execution at client side itself.}
  else { args.IsValid = true;//This will return to the server side. }    
 }

Aspx section:

  <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Value="1">select</asp:ListItem>
        <asp:ListItem Value="2">sdasda</asp:ListItem>
    </asp:DropDownList>
    <asp:CustomValidator ID="valCustmID" runat="server" ErrorMessage="*" ForeColor="Red"
        ValidationGroup="group1" ClientValidationFunction="ValidateFunction"></asp:CustomValidator>
    <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="group1" />

NOTE: Both the custom validator and the triggering button should have same validation group.

SERVER-SIDE VALIDATION

If you really want the validation server side see the code below:

     <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:DropDownList ID="DropDownList1" runat="server">
                <asp:ListItem Value="1">select</asp:ListItem>
                <asp:ListItem Value="2">sdasda</asp:ListItem>
            </asp:DropDownList>
            <asp:CustomValidator ID="CustomValidator1" OnServerValidate="commandAssigned" runat="server" ErrorMessage="*" ValidationGroup="group1"></asp:CustomValidator>
            <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="group1" />
        </ContentTemplate>
    </asp:UpdatePanel>

NOTE: Both the custom validator and the triggering button should have same validation group.

code behind event looks as below:

    protected void commandAssigned(object source, ServerValidateEventArgs args)
    {
        if (DropDownList1.SelectedItem.Value == "1")            
            args.IsValid = false;  //since you gave controlToValidate="DropDownList1"  this will display the error message.       
        else           
            args.IsValid = true;            
    }

Hope this helps..

Harun
  • 5,109
  • 4
  • 38
  • 60
  • 1
    You should *never* rely on client-side code alone to perform validation. You can use it in conjunction with server-side validation if you want, but you should still validate server-side in all cases. – Frédéric Hamidi Jun 30 '11 at 13:55
  • Will try it. I use the update panel because I'm changing the ddl on the fly (for users committed to the legacy I'm replacing) - and I thought I needed the update panel to redisplay, but I'll do as you suggest and see what happens. thanks – elbillaf Jun 30 '11 at 13:58
  • Frederic, thanks for the addendum on this one. I'll keep that in mind and work towards a server side solution, but I'm still going to try his solution to see if it gets me closer. I'm desperate. – elbillaf Jun 30 '11 at 14:01
  • Harun, sorry it took so long. I tried it. Still does not work. But thanks. I appreciate it. – elbillaf Jun 30 '11 at 14:15
  • @HARUN! Before using your code, I decided to just adding the ValidationGroup parameter from your code and it worked! I have some more testing to do, but this looks good! Thanks so much to both of you guys! (and I'm going to go read up on this validationgroup business!) – elbillaf Jun 30 '11 at 18:37
  • @TheFallibleFiend, The dropdownlist alone with AutoPostBack set to true is not triggering the custom validator OnServerValidate/ClientValidationFunction events. They both require a button with the same validation group as the customValidator to trigger them. Any Way i've updated my answer with both solutions. But better you avoid the ajax update panel because it causes performance issues as well as other unexpected issues. – Harun Jun 30 '11 at 18:38
  • Another minor problem ... I just noticed it's not validating the other fields now...going to try putting them all in validation group 1. I'll retry the solution with no AJAX. thanks. – elbillaf Jun 30 '11 at 18:50
  • Hmmm...I notice when I put multiple validators in 'group1' it does the non ddl ones and not the ddl. when I set those correctly, it will then report the invalid ddl. I'm going to try removing the ajax again to see if that helps. – elbillaf Jun 30 '11 at 18:54
  • If I understand the question, no. – elbillaf Jun 30 '11 at 18:56
  • Did the AutoPostBack="true" along with the same validation group as custom validator for the dropdownlist with out a button, triggered your OnServerValidate event? If still you did not get what i meant please do refer your question. – Harun Jun 30 '11 at 19:00
  • Okay. I understand. The answer is no. – elbillaf Jun 30 '11 at 19:12
2

i was facing the same issue.. but finally got the solution. it happens only when u have no item added in your drop down list.

vakas
  • 1,799
  • 5
  • 23
  • 40
1

You have to specify the control to validate using the aptly-named ControlToValidate property:

<asp:CustomValidator id="val_command_assigned" runat="server"
    ErrorMessage="* " Display="Static" OnServerValidate="commandAssigned"
    ControlToValidate="ddlCommandAssign" />

Otherwise, the custom validator will not perform any validation whatsoever.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • Thanks for response. I started with exactly that, but it did not work. HOWEVER, I tried again just now to make sure. Still doesn't work. I took it out because I found a number of references that said the validation will not be invoked if the control returns an empty string. (It did previously, but I changed it.) – elbillaf Jun 30 '11 at 13:49
  • @TheFallibleFiend, I don't think the empty string limitation applies to custom validators anyway. Does the handler get called if you temporarily remove the `UpdatePanel`? – Frédéric Hamidi Jun 30 '11 at 13:52
  • I just tried it - but it still fails to fire even after I remove the update panel. I should have thought of trying that before. – elbillaf Jun 30 '11 at 14:03
  • @TheFallibleFiend, you don't set the validator's `Enabled` or `Visible` property to `false`, or set a validation group in your code behind, right? – Frédéric Hamidi Jun 30 '11 at 14:19