Posts Tagged ‘ASP.NET Custom Validator Control’

ListValidator.cs Code

public class ListValidator : BaseValidator
{
public ListValidator()
{}

protected override bool ControlPropertiesValid()
{
Control ctrl = FindControl(ControlToValidate) as ListControl;
return (ctrl != null);
}

protected override bool EvaluateIsValid()
{
return this.CheckIfItemIsChecked();
}

protected bool CheckIfItemIsChecked()
{
ListControl listItemValidate = ((ListControl)this.FindControl(this.ControlToValidate));
foreach (ListItem listItem in listItemValidate.Items)
{
if (listItem.Selected == true)
return true;
}
return false;
}

protected override void OnPreRender(EventArgs e)
{
// Determines whether the validation control can be rendered
// for a newer (“uplevel”) browser.
// check if client-side validation is enabled.
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
Page.ClientScript.RegisterExpandoAttribute(this.ClientID, “evaluationfunction”, “CheckIfListChecked”);
this.CreateJavaScript();
}
base.OnPreRender(e);
}

protected void CreateJavaScript()
{
StringBuilder sb = new StringBuilder();
sb.Append(@”<script type=””text/javascript””>function CheckIfListChecked(ctrl){“);
sb.Append(@”var chkBoxList = document.getElementById(document.getElementById(ctrl.id).controltovalidate);”);
sb.Append(@”var chkBoxCount= chkBoxList.getElementsByTagName(“”input””);”);
sb.Append(@”for(var i=0;i<chkBoxCount.length;i++){“);
sb.Append(@”if(chkBoxCount.item(i).checked){“);
sb.Append(@”return true; }”);
sb.Append(@”}return false; “);
sb.Append(@”}</script>”);
Page.ClientScript.RegisterClientScriptBlock(GetType(), “JSScript”, sb.ToString());
}
}

Custom Validator Control – Usage – Client Side

<%@ Register TagPrefix=”CLV” Namespace=”WebApplication1.Concepts.Validators” assembly=”WebApplication1″%>

<form id=”form1″ runat=”server”>
<asp:CheckBoxList ID=”CheckBoxList1″ runat=”server”></asp:CheckBoxList>
<CLV:ListValidator runat=”server” ID=”custLstVal” ControlToValidate=”CheckBoxList1″ ErrorMessage=”At least one item in the checkboxlist should be checked”
EnableClientScript=”true”/>
<asp:RadioButtonList ID=”RadioButtonList1″ runat=”server”></asp:RadioButtonList>
<CLV:ListValidator runat=”server” ID=”custRadVal” ControlToValidate=”RadioButtonList1″ ErrorMessage=”At least one item in the radiobuttonlist should be checked”
EnableClientScript=”true”/>
<br />
<br />
<asp:Button ID=”Button1″ runat=”server”  Text=”Button” />
</form>

Web Page Code Behind Code

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> lstStr = new List<string>();
lstStr.Add(“Item 1”);
lstStr.Add(“Item 2”);
lstStr.Add(“Item 3”);
lstStr.Add(“Item 4”);
CheckBoxList1.DataSource = lstStr;
CheckBoxList1.DataBind();
RadioButtonList1.DataSource = lstStr;
RadioButtonList1.DataBind();
}
}

Advertisements

CustomValidator control is another validator control which is used to validate controls based on some custom logic that does not fall into the generic validations possible using the out of box other validator controls.
Following example explains how we can validate control using CustomValidator control both on client, server side.

Client Side Validation

<form id=”form1″ runat=”server”>
<div>
Prime Number:<br />
<asp:TextBox runat=”server” id=”txt2″ />
<asp:CustomValidator runat=”server” id=”custtxt2″ controltovalidate=”txt2″
errormessage=”Please enter prime number!” ValidationGroup=”123″ ClientValidationFunction=”CheckPrime”/>
</div>
</form>

Javascript

<script language=”JavaScript”>
function CheckPrime(sender, args)
{
var iPrime = parseInt(args.Value);
var iSqrt = parseInt(Math.sqrt(iPrime));
for (var iLoop=2; iLoop<=iSqrt; iLoop++)
if (iPrime % iLoop == 0)
{
args.IsValid = false;
return;
}
args.IsValid = true;
}
</script>

ServerSide Validation

<form id=”form2″ runat=”server”>
<div>
Prime Number:<br />
<asp:TextBox runat=”server” id=”txt1″ />
<asp:CustomValidator runat=”server” id=”custtxt1″ controltovalidate=”txt1″
errormessage=”Please enter prime number!” ValidationGroup=”234″ OnServerValidate=”PrimeNumberCheck” EnableClientScript=”false”/>
<br /><br />
<asp:Button runat=”server” id=”btnSubmt2″ text=”Ok” onclick=”btnSubmt2_Click” ValidationGroup=”234″ />
</div>
</form>

Webpage Code Behind C# Code

public void PrimeNumberCheck(object sender, ServerValidateEventArgs args)
{
int iPrime = Convert.ToInt32(args.Value);
int iLoop = 0;
int iSqrt = Convert.ToInt32(Math.Sqrt(iPrime));
for (iLoop = 2; iLoop <= iSqrt; iLoop++)
{
if (iPrime % iLoop == 0)
{
args.IsValid = false;
return;
}
}
args.IsValid = true;
}

protected void btnSubmt2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
btnSubmt2.Text = “Valid!”;
}
}

EnableClientScript=”false”