ASP.NET: Creating A Custom Validator Control

Code for Control: /App_Code/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
        Private _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 Overloads 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





Code on the ASPX page

<%@ Register TagPrefix="custom" Namespace="myControls" %>


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

2 comments:

  1. Example taken from SAMS ASP.NET 3.5 UNLEASHED

    ReplyDelete
  2. This post tells you how to create custom Validator. The steps are easy to perform. You will understand them in one go but it takes time to learn them. The program include basic coding concept. Try yourself to implement. Thanks.

    ReplyDelete