Using CustomValidator to enforce the user to fill at least one textbox control.

If you have a requirement in which you have many textbox controls and you want to enforce the user to fill at least one of them, then you can simply use a custom validator control with a client side function like this :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">
        function ValidatePhone(src, args) {
            var txtHomePhone = document.getElementById('<%= txtHomePhone.ClientID %>');
            var txtMobilePhone = document.getElementById('<%= txtMobilePhone.ClientID %>');
            var txtOfficePhone = document.getElementById('<%= txtOfficePhone.ClientID %>');

            if (txtHomePhone.value == '' && txtMobilePhone.value == '' && txtOfficePhone.value == '') {
                args.IsValid = false;
                return;
            }
            args.IsValid = true;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtHomePhone" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtMobilePhone" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtOfficePhone" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Enter at least one phone number"
            ValidateEmptyText="true" ClientValidationFunction="ValidatePhone" Display="Dynamic"
            ControlToValidate="txtHomePhone"></asp:CustomValidator>
        <asp:Button ID="btnValidate" runat="server" Text="Validate" />
    </div>
    </form>
</body>
</html>

No Comments