Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Creating Custom Validation Controls

In this final section, you learn how to create custom validation controls. We create two custom controls. First we create a LengthValidator control that enables you to validate the length of an entry in a form field. Next, we create an AjaxValidator control. The AjaxValidator control performs validation on the client by passing information back to a custom function defined on the server.

You create a new validation control by deriving a new control from the BaseValidator class. As its name implies, the BaseValidator class is the base class for all the validation controls, including the RequiredFieldValidator and RegularExpressionValidator controls.

The BaseValidator class is a MustInherit (abstract) class, which requires you to implement a single method:

  • EvaluateIsValid— Returns true when the form field being validated is valid.

The BaseValidator class also includes several other methods that you can override or otherwise use. The most useful of these methods is the following:

  • GetControlValidationValue— Enables you to retrieve the value of the control being validated.

When you create a custom validation control, you override the EvaluateIsValid() method and, within the EvaluateIsValid() method, you call GetControlValidationValue to get the value of the form field being validated.

Creating a LengthValidator Control

To illustrate the general technique for creating a custom validation control, in this section we will create an extremely simple one. It's a LengthValidator control, which enables you to validate the length of a form field.

The code for the LengthValidator control is contained in Listing 3.20.

Example 3.20. LengthValidator.vb

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace myControls

    ''' <summary>
    ''' Validates the length of an input field
    ''' </summary>
    Public Class LengthValidator
        Inherits BaseValidator

        Dim _maximumLength As Integer = 0

        Public Property MaximumLength() As Integer
            Get
                Return _maximumLength
            End Get
            Set(ByVal Value As Integer)
                _maximumLength = value
            End Set
        End Property

        Protected Overrides Function EvaluateIsValid() As Boolean
            Dim value As String = Me.GetControlValidationValue(Me.ControlToValidate)
            If value.Length > _maximumLength Then
                Return False
            Else
                Return True
            End If
        End Function
    End Class
End Namespace

Listing 3.20 contains a class that inherits from the BaseValidator class. The new class overrides the EvaluateIsValid method. The value from the control being validated is retrieved with the help of the GetControlValidationValue() method, and the length of the value is compared against the MaximumLength property.

The page in Listing 3.21 uses the LengthValidator control to validate the length of a comment input field (see Figure 3.16).

03fig16.jpg

Figure 3.16 Validating the length of a field with the LengthValidator control.

Example 3.21. ShowLengthValidator.aspx

<%@ Page Language="VB" %>
<%@ Register TagPrefix="custom" Namespace="myControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Length Validator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:Label
        id="lblComments"
        Text="Comments:"
        AssociatedControlID="txtComments"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtComments"
        TextMode="MultiLine"
        Columns="30"
        Rows="2"
        Runat="server" />
    <custom:LengthValidator
        id="valComments"
        ControlToValidate="txtComments"
        Text="(Must be less than 10 characters)"
        MaximumLength="10"
        Runat="server" />

    <br /><br />

    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />

    </div>
    </form>
</body>
</html>

Notice that the LengthValidator is registered at the top of the page with the <%@ Register %> directive. If you need to use the control in multiple pages in your application, then you can alternatively register the control in the <pages> section of your application's web configuration file.

Creating an AjaxValidator Control

In this section, we are going to create an extremely useful control named the AjaxValidator control. Like the CustomValidator control, the AjaxValidator control enables you to create a custom server-side validation function. Unlike the CustomValidator control, however, the AjaxValidator control enables you to call the custom validation function from the browser.

The AjaxValidator control uses AJAX (Asynchronous JavaScript and XML) to call the server-side validation function from the client. The advantage of using AJAX is that no postback to the server is apparent to the user.

For example, imagine that you are creating a website registration form and you need to validate a User Name field. You want to make sure that the User Name entered does not already exist in the database. The AjaxValidator enables you to call a server-side validation function from the client to check whether the User Name is unique in the database.

The code for the AjaxValidator control is contained in Listing 3.22.

Example 3.22. AjaxValidator.vb

Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace myControls

    ''' <summary>
    ''' Enables you to perform custom validation on both the client and server
    ''' </summary>
    Public Class AjaxValidator
        Inherits BaseValidator
        Implements ICallbackEventHandler

        Public Event ServerValidate As ServerValidateEventHandler

        Dim _controlToValidateValue As String

        Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
            Dim eventRef As String = Page.ClientScript.GetCallbackEventReference(Me, "","", "")

            ' Register include file
            Dim includeScript As String = Page.ResolveClientUrl("~/ClientScripts/AjaxValidator.js")
            Page.ClientScript.RegisterClientScriptInclude("AjaxValidator", includeScript)

            ' Register startup script
            Dim startupScript As String = String.Format("document.getElementById('{0}').evaluationfunction = 'AjaxValidatorEvaluateIsValid'", Me.ClientID)
            Page.ClientScript.RegisterStartupScript(Me.GetType(), "AjaxValidator", startupScript, True)

            MyBase.OnPreRender(e)
        End Sub

        ''' <summary>
        ''' Only do the AJAX call on browsers that support it
        ''' </summary>
        Protected Overrides Function DetermineRenderUplevel() As Boolean
            Return Context.Request.Browser.SupportsCallback
        End Function

        ''' <summary>
        ''' Server method called by client AJAX call
        ''' </summary>
        Public Function GetCallbackResult() As String Implements ICallbackEventHandler.GetCallbackResult
            Return ExecuteValidationFunction(_controlToValidateValue).ToString()
        End Function

        ''' <summary>
        ''' Return callback result to client
        ''' </summary>
        Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements ICallbackEventHandler.RaiseCallbackEvent
            _controlToValidateValue = eventArgument
        End Sub

        ''' <summary>
        ''' Server-side method for validation
        ''' </summary>
        Protected Overrides Function EvaluateIsValid() As Boolean
            Dim controlToValidateValue As String = Me.GetControlValidationValue(Me.ControlToValidate)
            Return ExecuteValidationFunction(controlToValidateValue)
        End Function

        ''' <summary>
        ''' Performs the validation for both server and client
        ''' </summary>
        Private Function ExecuteValidationFunction(ByVal controlToValidateValue As String) As Boolean
            Dim args As New ServerValidateEventArgs(controlToValidateValue, Me.IsValid)
            RaiseEvent ServerValidate(Me, args)
            Return args.IsValid
        End Function

    End Class

End Namespace

The control in Listing 3.22 inherits from the BaseValidator class. It also implements the ICallbackEventHandler interface. The ICallbackEventHandler interface defines two methods that are called on the server when an AJAX request is made from the client.

In the OnPreRender() method, a JavaScript include file and startup script are registered. The JavaScript include file contains the client-side functions that are called when the AjaxValidator validates a form field on the client. The startup script associates the client-side AjaxValidatorEvaluateIsValid() function with the AjaxValidator control. The client-side validation framework automatically calls this JavaScript function when performing validation.

The JavaScript functions used by the AjaxValidator control are contained in Listing 3.23.

Example 3.23. AjaxValidator.js

// Performs AJAX call back to server
function AjaxValidatorEvaluateIsValid(val)
{
    var value = ValidatorGetValue(val.controltovalidate);
    WebForm_DoCallback(val.id, value, AjaxValidatorResult, val,
AjaxValidatorError, true);
    return true;
}

// Called when result is returned from server
function AjaxValidatorResult(returnValue, context)
{
    if (returnValue == 'True')
        context.isvalid = true;
    else
        context.isvalid = false;
    ValidatorUpdateDisplay(context);
}

// If there is an error, show it
function AjaxValidatorError(message)
{
    alert('Error: ' + message);
}

The AjaxValidatorEvaluateIsValid() JavaScript method initiates an AJAX call by calling the WebForm_DoCallback() method. This method calls the server-side validation function associated with the AjaxValidator control. When the AJAX call completes, the AjaxValidatorResult() method is called. This method updates the display of the validation control on the client.

The page in Listing 3.24 illustrates how you can use the AjaxValidator control. This page handles the AjaxValidator control's ServerValidate event to associate a custom validation function with the control.

The page in Listing 3.24 contains a form that includes fields for entering a username and favorite color. When you submit the form, the values of these fields are inserted into a database table named Users.

In Listing 3.24, the validation function checks whether a username already exists in the database. If you enter a username that already exists, a validation error message is displayed. The message is displayed in the browser before you submit the form back to the server (see Figure 3.17).

03fig17.jpg

Figure 3.17 Using the AjaxValidator to check whether a username is unique.

It is important to realize that you can associate any server-side validation function with the AjaxValidator. You can perform a database lookup, call a web service, or perform a complex mathematical function. Whatever function you define on the server is automatically called on the client.

Example 3.24. ShowAjaxValidator.aspx

<%@ Page Language="VB" %>
<%@ Register TagPrefix="custom" Namespace="myControls" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    ''' <summary>
    ''' Validation function that is called on both the client and server
    ''' </summary>
    Protected Sub AjaxValidator1_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        If UserNameExists(args.Value) Then
            args.IsValid = False
        Else
            args.IsValid = True
        End If
    End Sub

    ''' <summary>
    ''' Returns true when user name already exists
    ''' in Users database table
    ''' </summary>
    Private Function UserNameExists(ByVal userName As String) As Boolean
        Dim conString As String = WebConfigurationManager.ConnectionStrings("UsersDB").ConnectionString
        Dim con As New SqlConnection(conString)
        Dim cmd As New SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName=@UserName", con)
        cmd.Parameters.AddWithValue("@UserName", userName)
        Dim result As Boolean =  False
        Using con
            con.Open()
            Dim count As Integer = CType(cmd.ExecuteScalar(), Integer)
            If count > 0 Then
                result = True
            End If
        End Using
        Return result
    End Function

    ''' <summary>
    ''' Insert new user name to Users database table
    ''' </summary>
    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim conString As String = WebConfigurationManager.ConnectionStrings("UsersDB").ConnectionString
        Dim con As New SqlConnection(conString)
        Dim cmd As New SqlCommand("INSERT Users (UserName,FavoriteColor) VALUES (@UserName,@FavoriteColor)", con)
        cmd.Parameters.AddWithValue("@UserName", txtUserName.Text)
        cmd.Parameters.AddWithValue("@FavoriteColor", txtFavoriteColor.Text)
        Using con
            con.Open()
            cmd.ExecuteNonQuery()
        End Using
        txtUserName.Text = String.Empty
        txtFavoriteColor.Text = String.Empty
    End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show AjaxValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:Label
        id="lblUserName"
        Text="User Name:"
        AssociatedControlID="txtUserName"
        Runat="server" />
    <asp:TextBox
        id="txtUserName"
        Runat="server" />
    <custom:AjaxValidator
        id="AjaxValidator1"
        ControlToValidate="txtUserName"
        Text="User name already taken!"
        OnServerValidate="AjaxValidator1_ServerValidate"
        Runat="server" />

    <br /><br />
    <asp:Label
        id="lblFavoriteColor"
        Text="Favorite Color:"
        AssociatedControlID="txtFavoriteColor"
        Runat="server" />
    <asp:TextBox
        id="txtFavoriteColor"
        Runat="server" />

    <br /><br />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" OnClick="btnSubmit_Click" />

    </div>
    </form>
</body>
</html>
  • + Share This
  • 🔖 Save To Your Account