استفاده از Custom Validator برای تایید اعتبار ListBox Control client side در ASP.Net
با سلام این یک مقاله کوتاه است که نحوه اجرای اعتبارسنجی برای کنترل ListBox با استفاده از Validator سفارشی در ASP.Net را توضیح میدهد.
اعتبار حداقل یک مورد در کنترل ListBox انتخاب شده
در کد زیر یک Validator سفارشی را اجرا می کنیم که استفاده از یک مورد در لیست کنترل با استفاده از روش ValidateListBox جاوا اسکریپت انتخاب کرده است را بررسی می کند.
<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" />
تایید حداقل یک مورد در کنترل ListBox
در کد زیر یک Validator سفارشی را اجرا می کنیم که بررسی می کند کنترل ListBox شامل حداقل یک مورد با استفاده از روش ValidateListBox جاوا اسکریپت باشد .
<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" />
امیدوارم قطعه کد بالا مفید باشد.