ASP.NET Validator Controls – Part2

Posted: December 5, 2010 in ASP.NET
Tags: , ,

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”
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s