The
CustomValidator
control also exposes a method,
ServerValidate
, that must be handled by the form's server-side code and referenced when the control is used with the
OnServerValidate=""
attribute. It is possible to create very advanced
CustomValidator
validation logic, but for this example, we will just check to see if the value entered is a perfect square (an integer raised to the power of 2) or not. Listings 8.5 and 8.6 show the ASPX file and its codebehind used for this validation. For this example, only server-side validation is being implemented, which is frequently all that is possible with custom validation because they often rely on remote data stores to perform their
tasks
.
Listing 8.5 Adding custom validation to a text box (Example0905.aspx).
<%@ Page language="c#" Codebehind="Example0905.aspx.cs" Src="Example0905.aspx.cs"
AutoEventWireup="false" Inherits="validate.Example0905" %>
<HTML>
<HEAD>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
</HEAD>
<body>
<form method="post" runat="server" ID="Form1">
<asp:Label ID="errorMessage" Runat="server"></asp:Label>
<table>
<tr>
<td>
Enter a Perfect Square (the square of an integer):
</td>
<td>
<asp:textbox runat="Server" columns="30"
id="square"></asp:textbox>
</td>
<td>
<asp:CustomValidator Runat="server"
ID="square_custom" Display="Dynamic" OnServerValidate="validateSquare"
EnableClientScript="False">
*
</asp:CustomValidator>
</td>
</tr>
</table>
<asp:button id="save_button" runat="Server"
text="Save"></asp:button>
</form>
</body>
</HTML>
Listing 8.6 Adding custom validation to a text box (Example0905.aspx.cs).
protected void validateSquare(object sender,
System.Web.UI.WebControls.ServerValidateEventArgs e)
{
int _square;
int _sqrt;
try
{
_square = Int32.Parse(square.Text.ToString());
}
catch
{
e.IsValid = false;
return;
}
try
{
_sqrt =
Int32.Parse(Math.Sqrt(Double.Parse(_square.ToString())).ToString());
}
catch
{
e.IsValid = false;
return;
}
e.IsValid = true;
}
This example takes advantage of error handlers to determine whether or not the square root of the value entered into the "square" text box is an integer. If no error is raised when converting the value itself or its square root into an integer value, the value entered must be a perfect square. Otherwise, the value must not be a perfect square. It is interesting to note that the event handler
validateSquare
does not return a value, but instead sets the value of the
ServerEventArgs
object's
IsValid
property to
true
or
false
, as appropriate. Although this is a very simple example, custom validation controls can be as simple or as complex as your business needs
dictate
.