asp.netcustomvalidatorvalidationsummary

Asp.Net - CustomValidator's ErrorMessage - Only show on ValidationSummary - Not other places


Here is ASPX :

<form id="form1" runat="server">
    <div>
        <fieldset style="width: 160px">

            <legend>Select your skills</legend>

            <asp:ValidationSummary ID="ValidationSummary1" runat="server" />

            <asp:CheckBoxList ID="cblCourses" runat="server" RepeatColumns="2">

                <asp:ListItem>Asp.net</asp:ListItem>

                <asp:ListItem>C#</asp:ListItem>

                <asp:ListItem>VB</asp:ListItem>

                <asp:ListItem>WCF</asp:ListItem>

                <asp:ListItem>Jquery</asp:ListItem>

                <asp:ListItem>JavaScript</asp:ListItem>

            </asp:CheckBoxList>

            <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>

            <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select at least one skills." ClientValidationFunction="validateCheckBoxList" Display="Dynamic" ForeColor="Red"></asp:CustomValidator>

            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" Style="height: 26px" />

        </fieldset>

    </div>
</form>

And here is javascript :

<script type = "text/javascript">

    function validateCheckBoxList(source, args) {

        var chkListModules = document.getElementById('<%= cblCourses.ClientID %>');

        var chkListinputs = chkListModules.getElementsByTagName("input");

        for (var i = 0; i < chkListinputs.length; i++) {

            if (chkListinputs[i].checked) {

                args.IsValid = true;

                return;

            }

        }

        args.IsValid = false;

    }

</script>

The problem is when i click on btnSubmit button two error messages show up.
One in ValidationSummary.
The other one next to btnSubmit button.
How can i tell CustomValidator to show it's message only in ValidationSummary, not other places?


Solution

  • You can wrap the CustomValidator in a div or span with display:none; the error still shows in the summary but nowhere else: -

    <span style="display:none;"> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select at least one skills." ClientValidationFunction="validateCheckBoxList" Display="Dynamic" ForeColor="Red"></asp:CustomValidator> </span>

    You should create a class for your div/span instead of inlining the style, this is just to demonstrate it works.