views:

693

answers:

2

I have a page where a user can either select a vendor via dropdown or enter a vendor number via textbox. One or the other must have a value. I can do this in javascript easily but how can I do this using a custom validator provided by ajax all on the client side?

Edited

 Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
    If Page.IsValid Then
        //save stuff
    End If
 End Sub

Sub ServerValidation(ByVal source As Object, ByVal args As ServerValidateEventArgs) Handles ValidPage.ServerValidate

     Try
         ' Test whether the value entered into the text box is even.
         Dim num As Integer = Integer.Parse(args.Value)
         args.IsValid = ((num Mod 2) = 0)

     Catch ex As Exception
         args.IsValid = False
End Try

End Sub

Protected Sub ValidPage_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
    Try
        args.IsValid = (Not String.IsNullOrEmpty(Me.txtVendnum.Text) OrElse Me.DropDownList1.SelectedIndex <> 0)
    Catch e As Exception
        DirectCast(source, CustomValidator).ErrorMessage = "You must Choose a Vendor"
        args.IsValid = False
    End Try
End Sub
<script type="text/javascript" language="javascript" >
   function ClientValidate(sender, args) {
       // Get Both form fields
       var ddlvalue = document.getElementById('<%=DropDownList1.ClientID%>');
       var txtValue = document.getElementById('<%=txtVendnum.ClientID %>');

    // do you client side check to make sure they have something
       if (txtValue.value == '' && ddlvalue.value == '0') {

        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;
    }

}

<asp:DropDownList ID="DropDownList1" runat="server" 
                    DataSourceID="SqlDataSource1" ValidationGroup="Save" DataTextField="vmvnnm" DataValueField="vmvend" >
                    </asp:DropDownList>

<asp:TextBox ID="txtVendnum" ValidationGroup="Save" runat="server"></asp:TextBox><br />

                        <asp:CustomValidator ID="ValidPage" ValidationGroup="Save" runat="server" ClientValidationFunction="ClientValidate" ErrorMessage="CustomValidator" 
                            SetFocusOnError="True" ControlToValidate="txtVendnum" EnableClientScript="true" Display="Static" OnServerValidate = "ServerValidation" ></asp:CustomValidator>

//other stuff. A different validator group, html editor, etc


<td>
                        <asp:ImageButton ID="ImageButton1" CausesValidation = "true"     ValidationGroup="Save" OnClick="ImageButton1_Click" runat="server" ImageUrl="../images/bttnSave.gif" />

                    </td>
+1  A: 

You need to set the ClientValidationFunction property of your custom validator to the name of a javascript function that will exist on the page.

The function needs to take in two arguments, one of which is the "args" argument which you will set to be valid or not. An example based on the MSDN page for CustomValidator:

 function ClientValidate(source, args)
   {         
      if (myTextBox.Value == "" && myDropDown.Value == "" )
      {
         args.IsValid=false;
      }
      else {args.IsValid=true};
   }
womp
You might want to think of doing 1 control, an Ajax Auto Complete on a textbox. there are tons of great libraries out there to help : (YUI,jQuery)
BigBlondeViking
+1 to that comment.
womp
both my sender and args are undefined. Am i missing something??
Eric
sorry that comment was meant for the question... the web is getting to fast :)
BigBlondeViking
+1  A: 
<asp:CustomValidator ID="ValidPage" runat="server" 
    EnableClientScript="true"
    ClientValidationFunction="My.util.VendnumCheck"
    OnServerValidate="ValidPage_ServerValidate"
    ControlToValidate="txtVendnum" 
    ErrorMessage="You must Choose a Vendor" 
    SetFocusOnError="True" 
    ValidationGroup="Save">
</asp:CustomValidator>

ClientValidationFunction="My.util.VendnumCheck"

You should also be doing Server Side validation!

protected void ValidPage_ServerValidate(object source, ServerValidateEventArgs args)
{
    try
    {
        args.IsValid = (!string.IsNullOrEmpty(this.txtVendnum.Text) || this.DropDownList1.SelectedIndex != 0);
    }
    catch (Exception e)
    {
        ((CustomValidator)source).ErrorMessage = "You must Choose a Vendor";
        args.IsValid = false;
    } 
}


protected void Button_Click(object sender, EventArgs e)
{
     if (Page.IsValid)
     { 
         //do work
     }
}

JS:

My.util.VendnumCheck = function(sender, args) {
try {
        // Get Both form fields
        var ddlvalue = document.getElementById("<%=this.DropDownList1.ClientID %>");
        var txtValue = document.getElementById("<%=this.txtVendnum.ClientID %>").value;

        // do you client side check to make sure they have something 
        if ( txtValue.length < 1 && ddlvalue.selectedIndex != 0)
            args.IsValid = false;

        args.IsValid = true; 
    }
    catch (ex) {
        My.logError(ex);
        args.IsValid = false;
    }
}

try having this JS method called on Blur of the text box, see if it picks up the validator...

My.util.callMyValidators = function() {
    // Clean Up Infragistics Ids
    var cleanid = this.id.replace(/^igtxt/i, "");

    if (Page_Validators == null) {
        alert("My.util.callMyValidators when Page_Validators is null");
    }
    var found = 0;

    for (var i = 0; i < Page_Validators.length; i++) {
        if (Page_Validators[i].controltovalidate === cleanid) {
            found++;
            ValidatorValidate(Page_Validators[i]);
        }
    }

    if (found === 0) {
        alert("My.util.callMyValidators did find any matching validators for " + cleanid);
    }
}
BigBlondeViking
ok, how does the function receive those parameters? I'm a bit lost. It doesn't seem as though my function is getting called.
Eric
u need to add ControlToValidate="txtVendnum"
BigBlondeViking
u really need to add a server validation function as well
BigBlondeViking
Yeah, I'm sorry I had that, i just didn't include it in the code i presented. Also, I am getting to the function, but my parameters are undefined...source and args. I still don't see where to send those parameters. Thanks for you extra help. +1 and +1 on your comment
Eric
the Image button has CauseValidation = true as well?
BigBlondeViking
Yes, it has causes validation. And actually, the only reason i was getting to that function is because i had it on the onclick event of the button. I'm not getting to that function anymore.
Eric
ahhh yea rip it out the button click... thats no good... the validator isnt firing... is the server validate firing? did u set EnableClientScript="true"?
BigBlondeViking
Yes...i set that = True. I'll post my custom validator above under edit. On server side of the button click I check the values and insert if the textbox or the ddl are not empty. That works fine. Im just not getting to that function...I'll post that function above too.
Eric
FYI: you should let the CustomValidator do you Server side Validation check: in your button Event you just need to check if (!Page.IsValide)return;
BigBlondeViking
In FireFox, Using FireBug, go to the DOM Tab, do you see the following: Page_ValidationActive = true; and in the Page_Validators array, a validator that is has controltovalidate = your textbox's client id?
BigBlondeViking
Add the server validate to front end and backend, see if the server side fires when you click the button.
BigBlondeViking
Yes I saw all of them.
Eric
Btw, thanks for informing me about that tool.I didn't have it before.
Eric
U must use firebug... it almost a requirement for webdev...
BigBlondeViking
Didn't fire off.
Eric
btw...i +1 one of your questions because of your extended help
Eric
Ur sure the ImageButton.CausesValidation="true"? You might want to rip out all the validation groups and see if you can get them the fire for whole page validation...
BigBlondeViking
I still can't get them to fire.
Eric
It's going straight to the button click event
Eric
oh and yes I did add the causes validation. Still not firing
Eric
Re-post all your edited code in the Edit section... Try adding a simple required field validator against the text box... see if it fires
BigBlondeViking
Also look at the link from WOMP's answer : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspxit might help
BigBlondeViking
Your other validation group is working im guessing?
BigBlondeViking
yes. It is working
Eric
notice your points. thanks again for all the help.
Eric
Try that last JS function on blur... i use it to force validation on the fly for my forms...
BigBlondeViking
I'm thinking I'm going to just use a regular javascript popup...just call that javascript function.
Eric
onblur of what? the button?
Eric
the textbox, ( this is just a test to ensure the validator and textbox are associated )
BigBlondeViking
Hey I got it! First thing this morning. Believe it or not All I had to do for whatever reason is change the controltovalidate to the DropDownList. Thanks for all of your help! Hey,Are you a Vikings fan by any chance?
Eric
no, I am a tall blonde dude with Nordic blood... that rapes and pillages NYC :) there is always something...
BigBlondeViking