Sunday, April 20, 2014

Validate ASP.Net ListBox control using JavaScript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default11.aspx.cs" Inherits="Default11" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    
<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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
  
<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>
<asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

0 comments:

Post a Comment