Performing Custom Validation using the CustomValidator Control (C# 2005)

The CustomValidator controls are used to enforce validations which cannnot be enforced with the standard validation controls provided by Asp.Net. The CustomValidator controls can be used to perform validations on server-side as well as on the client-side.

The CustomValidator control calls a user-defined function to perform validations that the standard validators cannot handle. The user-defined function, also referred to as the custom function can execute on the server or in the client-side script, such as JScript or VBScript or c#. For client-side custom validation, the name of the custom function must be identified in the ClientValidationFunction property. The custom function must be written as a form function, say, myvalidator(source, arguments). Note that the ‘source’ is the client-side CustomValidator object, and ‘arguments’ is an object with two properties, Value and IsValid. The Value property is the value to be validated and the IsValid property is a Boolean and is used to set the return result of the validation.
For server-side custom validation, place your custom validation code in the validator’s OnServerValidate delegate.


Properties of CustomValidator control

ControlToValidate

Use this property to Specify the ID of the control to be validated.

Display

This property determines how the error message contained in the text property is to be displayed. Possible values are Static, Dynamic and None; the default value is Static.

ErrorMessage

This property specifies the error message that is to be displayed in the ValidationSummary control. This error message is displayed by the control when the Text property is not set.

IsValid

This property contains the value true when the validation check succeeds and false when the validation check fails.

Text

This property sets the error message displayed by the control.

Methods of CustomValidator control

OnServerValidate

This method raises the ServerValidate event.

Validate

This method performs validation and updates the IsValid property.

Events of CustomValidator control

ServerValidate

This event represents the function for performing the server-side validation.

The following sample shows how to use the CustomValidator control.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script language="C#" runat="server">

void CustomValidator_ServerValidate(object s, ServerValidateEventArgs e)
{
if (IsConnectionProper() == true)
{
//Response.Write("OK");
e.IsValid = true;

}
else
{
//Response.Write("Not OK"); 
e.IsValid = false;
}
}


bool IsConnectionAvailable()
{
System.Uri objUrl = new System.Uri(txtWebsite.Text);
WebRequest objWebReq;
try
{
objWebReq = System.Net.WebRequest.Create(objUrl);
return true;
}
catch (Exception ex)
{
return false;
}
}


bool IsConnectionProper()
{

if (IsConnectionAvailable() == true)
{

string URL = txtWebsite.Text;
//Create a request for the URL. 
WebRequest request = WebRequest.Create(URL);
try
{
//Get the response. 
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Display the status. 
//Response.Write(response.StatusDescription);
//Response.Write("\n Site Exists.");
return true;
}
catch (Exception exc)
{

//Response.Write("\n Site does not exists.");
return false;
}

} //if
else
{
//Response.Write("Syntax not correct");
return false;
}
}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label id="lblWebsite" Text="Website" 
Width="200px" Font-Size="12px" 
runat="server" />
<asp:TextBox ID="txtWebsite" 
MaxLength="100" 
Width="400px" runat="server" /> 
<asp:RequiredFieldValidator ID="txtWebsiteValidator" 
ControlToValidate="txtWebsite" 
Text="*" ErrorMessage="Website is Missing"
runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" 
ControlToValidate="txtWebsite" 
Text="Invalid URL" 
ValidationExpression="http://\S+\.\S+" 
runat="server" />
<asp:CustomValidator ID="CustomValidator1" 
ControlToValidate="txtWebsite" 
OnServerValidate="CustomValidator_ServerValidate" 
Display="Dynamic" 
Text="URL not active" 
runat="Server" /> 
</div>
</form>
</body>
</html>


In the above example, we have created a custom validation subroutine ‘CustomValidator_ServerValidate’ that checks whether a website URL is active or not. Note that the custom validation subroutine is not called when the control being validated does not contain any data. We have used the RequiredFieldValidator control to check for an empty form field.

The subroutine, void CustomValidator_ServerValidate(object s, ServerValidateEventArgs e) checks whether the URL entered in the web site address field, by calling function IsConnectionAvailable. If it is active, the value True is assigned to the IsValid property, otherwise, the value False is assigned.