验证下拉列表或文本框

时间:2009-07-22 19:00:41

标签: c# asp.net vb.net visual-studio-2008 validation

我有一个页面,用户可以通过下拉列表选择供应商,也可以通过文本框输入供应商编号。一个或另一个必须有一个值。我可以在javascript中轻松完成此操作但是如何使用ajax在客户端提供的自定义验证器来完成此操作?

被修改

 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>

2 个答案:

答案 0 :(得分:1)

您需要将自定义验证程序的ClientValidationFunction属性设置为页面上将存在的javascript函数的名称。

该函数需要接受两个参数,其中一个参数是你将设置为有效的“args”参数。示例based on the MSDN page for CustomValidator

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

答案 1 :(得分: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”

您还应该进行服务器端验证!

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

尝试在文本框的Blur上调用此JS方法,看看它是否选择了验证器......

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