2009-07-22 10 views
0

J'ai une page où un utilisateur peut sélectionner un fournisseur via une liste déroulante ou entrer un numéro de fournisseur via une zone de texte. L'un ou l'autre doit avoir une valeur. Je peux le faire en javascript facilement, mais comment puis-je le faire en utilisant un validateur personnalisé fourni par ajax tous sur le côté client?Validation de la liste déroulante OU de la zone de texte

Edité

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> 
+0

Vous voudrez peut-être penser de faire 1 contrôle, un Ajax Auto Complete sur une zone de texte. Il ya des tonnes de grandes bibliothèques là-bas pour aider: (YUI, jQuery) (Il appartient ici désolé ~) – BigBlondeViking

Répondre

1
<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"

Vous devez également être en train de faire du serveur de validation de côté!

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

essayer d'avoir cette méthode JS appelé flou de la zone de texte, voir si elle prend le validateur ...

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); 
    } 
} 
+0

ok, comment la fonction reçoit ces paramètres? Je suis un peu perdu. Il ne semble pas que ma fonction soit appelée. – Eric

+1

Vous devez ajouter ControlToValidate = "txtVendnum" – BigBlondeViking

+1

Vous avez vraiment besoin d'ajouter une fonction de validation de serveur ainsi – BigBlondeViking

1

Vous devez définir la propriété ClientValidationFunction de votre validateur personnalisé au nom d'une fonction javascript qui existe sur la page .

La fonction doit prendre deux arguments, dont l'argument "args" que vous définissez comme valide ou non. Un exemple based on the MSDN page for CustomValidator:

function ClientValidate(source, args) 
    {   
     if (myTextBox.Value == "" && myDropDown.Value == "") 
     { 
     args.IsValid=false; 
     } 
     else {args.IsValid=true}; 
    } 
+1

Vous voudrez peut-être penser à faire un contrôle, un Ajax Auto Complete sur une zone de texte. il ya des tonnes de grandes bibliothèques là-bas pour aider: (YUI, jQuery) – BigBlondeViking

+0

+1 à ce commentaire. – womp

+0

à la fois mon expéditeur et args sont indéfinis. Suis-je manquer quelque chose ?? – Eric

Questions connexes