简体   繁体   English

ASP.NET自定义验证器客户端和服务器端验证

[英]ASP.NET Custom Validator Client side & Server Side validation

In my web page I'm trying to preform validation on the client side and the server side. 在我的网页中,我试图在客户端和服务器端执行验证。 if the drop down and the text box are empty I need to show an error message but if one of them is filled out the validation should pass. 如果下拉列表和文本框为空,我需要显示一条错误消息,但是如果其中之一已填写,则验证应该通过。 Is there way to create one CustomValidator for both controls?? 有没有办法为两个控件创建一个CustomValidator? I have a feeling I'm not doing it right. 我觉得我做的不对。

Client Side code: 客户端代码:

  <div> <table> <tr> <td> <asp:DropDownList ID="ddlStates" runat="server" Width="128px"> <asp:ListItem></asp:ListItem> <asp:ListItem>Nevada</asp:ListItem> <asp:ListItem>Uta</asp:ListItem> <asp:ListItem>Oregon</asp:ListItem> </asp:DropDownList> </td> <td> <asp:CustomValidator ID="cvddlState" runat="server" ClientValidationFunction="StatesCheck" OnServerValidate="ServerValidation" ErrorMessage="(*) State is required" ForeColor="Red" Display="Dynamic"></asp:CustomValidator> </td> </tr> <tr> <td> <asp:TextBox ID="txtStates" runat="server"></asp:TextBox> </td> <td> <asp:CustomValidator ID="cvtxtStates" runat="server" ValidateEmptyText="true" ClientValidationFunction="StatesCheck" OnServerValidate="ServerValidation" ControlToValidate="txtStates" ErrorMessage="(*) Text cannot be empty" ForeColor="Red" Display="Dynamic"></asp:CustomValidator> </td> </tr> <tr> <td> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> </td> </tr> </table> </div> <div id="divErrorMessage" runat="server" class="alert alert-danger" visible="false"></div> <script type="text/javascript"> 'Use Strict'; function StatesCheck(source, args) { var ddlStates = document.getElementById("<%=ddlStates.ClientID%>"); var txt = document.getElementById('<%=txtStates.ClientID%>').value; var state = ddlStates.options[ddlStates.selectedIndex].value; if (ddlStates !== null) { if ((state === "") && (txt === "")) { args.IsValid = false; } else { args.IsValid = true; } } } </script> 

Server Side Code: 服务器端代码:

 Public Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click Try divErrorMessage.Visible = False divErrorMessage.InnerText = "" Dim ddlSelection As String = ddlStates.SelectedItem.Text Dim statesText As String = txtStates.Text.Trim() If statesText = String.Empty And ddlSelection = String.Empty Then Else divErrorMessage.Visible = True divErrorMessage.InnerText = "(*) Text cannot be empty" End If Catch ex As Exception End Try End Sub Protected Sub ServerValidation(source As Object, args As ServerValidateEventArgs) If (ddlStates.SelectedItem.Text = String.Empty) And (txtStates.Text.Length = 0) Then args.IsValid = False Else args.IsValid = True End If End Sub 

Are you getting an answer from both codes on Server Side and Client Side? 您是否从服务器端和客户端上的两个代码中都得到了答案? I want to answer the Server Side 我想回答服务器端

Protected Sub ServerValidation(source As Object, args As ServerValidateEventArgs)
        If (ddlStates.SelectedItem.Text = String.Empty) And (txtStates.Text.Length = 0) Then
            args.IsValid = False
        Else
            args.IsValid = True
        End If

    End Sub

Based on my expirience, Im not quite good in ASP.net but based on ypur code above, theres nothing wrong however the part you are saying but if one of them is filled out the validation should pass doesnt show here can you please try to do this one. 根据我的经验,我在ASP.net中的表现不是很好,但是基于上面的ypur代码,没有什么错,但是您要说的部分却是错误的,但是but if one of them is filled out the validation should pass没有通过,请您尝试这样做这个。

 Protected Sub ServerValidation(source As Object, args As ServerValidateEventArgs)
            If (ddlStates.SelectedItem.Text = String.Empty) Or (txtStates.Text.Length = 0) Then
                args.IsValid = False
Else
                args.IsValid = True
            End If

        End Sub

or maybe 或者可能

Protected Sub ServerValidation(source As Object, args As ServerValidateEventArgs)
        If (ddlStates.SelectedItem.Text = String.Empty) And (txtStates.Text.Length = 0) Then
            args.IsValid = False
        ElseIf (ddlStates.SelectedItem.Text <> String.Empty) then
          args.IsValid = True
        ElseIf (txtStates.Text <> "") then
          args.IsValid = True
        Else

            args.IsValid = True
        End If

    End Sub

This is a snippet where you can evaluate both controls with a CustomValidator 这是一个片段,您可以在其中使用CustomValidator评估两个控件

<asp:CustomValidator ID="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="input failed" ClientValidationFunction="myFunction"></asp:CustomValidator>

<script type="text/javascript">
    function myFunction(sender, element) {
        if (document.getElementById("<%= ddlStates.ClientID %>").selectedIndex == 0 && document.getElementById("<%= txtStates.ClientID %>").value != "") {
            element.IsValid = true;
        } else {
            element.IsValid = false;
        }
    }
</script>

You can use client side validation for the above scenario. 您可以将客户端验证用于上述情况。

  <div>
        <table>
            <tr>
                <td>
                    <asp:DropDownList ID="ddlStates" runat="server" Width="128px">
                        <asp:ListItem></asp:ListItem>
                        <asp:ListItem>Nevada</asp:ListItem>
                        <asp:ListItem>Uta</asp:ListItem>
                        <asp:ListItem>Oregon</asp:ListItem>
                    </asp:DropDownList>
                </td>

            </tr>
            <tr>
                <td>
                    <asp:TextBox ID="txtStates" runat="server"></asp:TextBox>
                </td>


            </tr>
            <tr>
                <td>
                    <label id="lbltxtstate" style="display: none;">Please select a state or enter a state.</label>
                    <br />
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return validateState();" />
                </td>
            </tr>
        </table>
    </div>

    <script type="text/javascript">
    function validateState(){
            if (($('#<%=ddlStates.ClientID %> option:selected').text() == "") && ($('#<%=txtStates.ClientID %>').val() == "")) {

            $('#lbltxtstate').attr('style', 'display:block');
            $('#lbltxtstate').attr('style', 'color:red');
            return false;
        }
        else {           
               $('#lbltxtstate').attr('style', 'display:none');
               return true;
        };

    }
    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM