Search code examples
asp.netvalidationwebformsaspxgridviewrequiredfieldvalidator

Required Field Validator for Combination of Textboxes


I have three Textboxes :

  1. Total Weight: <asp:TextBox runat="server" ID="TxtWt" Width="100px" ValidationGroup="AddComplexIng"></asp:TextBox>
  2. Min Weight: <asp:TextBox runat="server" ID="TxtMinRnge" Width="100px" ValidationGroup="AddComplexIng"></asp:TextBox>
  3. Max Weight: <asp:TextBox runat="server" ID="TxtMaxRnge" Width="100px" ValidationGroup="AddComplexIng"></asp:TextBox>

How can I use a required field validator so that following validation is achieved:

a. User enters values in all three textboxes i.e. Total Weight, Max Weight & Min Weight.

b. User enters atleast one : either user enters value for Total weight and leave min & max weight empty or user can leave Total weight empty and will have to enter both min & max weight.


Solution

  • You can use a CustomValidator.

    <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Input incorrect" ClientValidationFunction="myValidator" ValidationGroup="AddComplexIng"></asp:CustomValidator>
    
    <script type="text/javascript">
        function myValidator(oSrc, args) {
            var a = document.getElementById('<%= TxtWt.ClientID %>').value;
            var b = document.getElementById('<%= TxtMinRnge.ClientID %>').value;
            var c = document.getElementById('<%= TxtMaxRnge.ClientID %>').value;
    
            if (a != "" && b != "" && c != "") {
                args.IsValid = true;
            } else if (a != "" && b == "" && c == "") {
                args.IsValid = true;
            } else if (a == "" && b != "" && c != "") {
                args.IsValid = true;
            } else {
                args.IsValid = false;
            }
        }
    </script>