Validating ASP.Net ListBox Control client side using Custom Validator
 
Author:
Filed Under: ASP.Net  |  Snippets
Published Date: Mar 25, 2010
Views: 5338
 

Abstract: Here Mudassar Ahmed Khan has provided a snippet to validate ASP.Net ListBox Control client side using Custom Validators

Comments:  2

 

This is a short article describing how to implement validation for ASP.Net ListBox Control using Custom Validator in ASP.Net.
Validate at least one item is selected in ASP.Net ListBox Control
Below I have implemented an ASP.Net Custom Validator that checks whether use has selected atleast one item in the ASP.Net ListBox Control using ValidateListBox JavaScript method.
<asp:ListBox ID="ListBox1" runat="server" SelectionMode = "Multiple">
<asp:ListBox ID="ListBox1" runat="server" SelectionMode = "Multiple">
    <asp:ListItem Text = "Apple" Value = "1"></asp:ListItem>
    <asp:ListItem Text = "Mango" Value = "2"></asp:ListItem>
    <asp:ListItem Text = "Orange" Value = "3"></asp:ListItem>
</asp:ListBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="*Required"
ClientValidationFunction = "ValidateListBox"></asp:CustomValidator>
<script type = "text/javascript">
function ValidateListBox(sender, args) {
    var options = document.getElementById("<%=ListBox1.ClientID%>").options;
    for (var i = 0; i < options.length; i++) {
        if (options[i].selected == true) {
            args.IsValid = true;
            return;
        }
    }
    args.IsValid = false;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button" />
 
Validate at least one item present in ASP.Net ListBox Control
Below I have implemented an ASP.Net Custom Validator that checks whether ASP.Net ListBox Control contains at least one item using ValidateListBox JavaScript method.
<asp:ListBox ID="ListBox1" runat="server" SelectionMode = "Multiple">
</asp:ListBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="*Required"
ClientValidationFunction = "ValidateListBox"></asp:CustomValidator>
<script type = "text/javascript">
function ValidateListBox(sender, args) {
    var options = document.getElementById("<%=ListBox1.ClientID%>").options;
    if (options.length > 0) {
        args.IsValid = true;
    }
    else {
        args.IsValid = false;
    }       
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button" />
 
Hope you find the above code snippets useful.








Related Articles



Comments



Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit