Watch this example on YouTube:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataListWithCustomValidator.aspx.cs" Inherits="WebApplication1.DataListWithCustomValidator" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function ValidateNames(source, args) {
var ctr = 0
var FirstName = ""
var LastName = ""
var dataList = document.getElementById('<%= DataList1.ClientID %>')
var input = dataList.getElementsByTagName("input")
var custValidator = document.getElementById('<%= CustomValidator1.ClientID %>')
var ErrorMessage = ""
for (var i = 0; i < input.length; i++) {
if (input[i].type == "text") {
if (input[i].id.indexOf("txtFirstName") != -1) {
ctr++
FirstName = input[i].value
}
if (input[i].id.indexOf("txtLastName") != -1) {
LastName = input[i].value
if ((LastName != "" && FirstName == "") || (LastName == "" && FirstName != "")) {
args.IsValid = false
if (ErrorMessage == "") {
ErrorMessage = "Customer Number " + ctr + " - ensure both names are entered";
}
else {
ErrorMessage = ErrorMessage + "\n - Customer Number " + ctr + " - ensure both names are entered";
}
}
FirstName = ""
LastName = ""
}
}
}
if (!args.IsValid) {
source.errormessage = ErrorMessage;
//custValidator.setAttribute("errormessage", ErrorMessage)
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="FirstName"></asp:Label>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="LastName"></asp:Label>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<br />
</ItemTemplate>
</asp:DataList>
<asp:Button ID="Button1" runat="server" Text="Submit" ValidationGroup="test" />
</div>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
HeaderText="Please, correct the following errors:"
ShowMessageBox="true" ShowSummary="false" ValidationGroup="test" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="" Text="" Display="None"
ClientValidationFunction="ValidateNames" ValidationGroup="test"></asp:CustomValidator>
</form>
</body>
</html>
CODE BEHIND
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
public partial class DataListWithCustomValidator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = LoadData();
DataList1.DataSource = dt;
DataList1.DataBind();
}
private DataTable LoadData()
{
DataTable dt = new DataTable();
dt.Columns.Add("FName");
dt.Columns.Add("LName");
dt.Rows.Add(new object[] { "", "" });
dt.Rows.Add(new object[] { "", "" });
dt.Rows.Add(new object[] { "", "" });
return dt;
}
}
}
No comments:
Post a Comment