This is my personal blog. The views expressed on these pages are mine alone and not those of my employer.

Tuesday, 19 January 2010

Validatation for Custom User Controls

Recently I stumbled across the problem of needing to validate user input supplied to a Custom User Control.  Usually validation is simply the case of dragging one of the excellent validation controls onto the page and pointing it towards the control you wish to validate.

Custom User Control's however are a different story.  These are controls written by a developer to carry out a function which no other existing controls can.  As they have been written from the ground up, they cannot be simply associated to a validation control without further work.

To allow a Custom User Control to be validated the first thing which is required is the addition of <ValidationPropertyAttribute("value")>.  This specifies the property which supplies the string to be validated, where "value" is the name of the property.

Secondly the ControlToValidate="" property of validation control on the page should be the ID of the user control, colon(:), then the ID of the control to which 'value' is associated.

For example I had a control named cboTask which had <ValidationPropertyAttribute("value")> defined within it where value was a property which returned the current value of a DropDownList (DropDownList1) which was contained within cboTask.  In order to validate that the user selected an option I used the RequiredFieldValidator with the ControlToValidate="cboTask:DropDownList1".

   1:  <ValidationPropertyAttribute("value")> _
   2:  Partial Public Class ctlDropDownList
   3:      Inherits System.Web.UI.UserControl
   6:   Public Property value() As String
   7:          Get
   8:              Return DropDownList1.SelectedValue.Trim()
   9:          End Get
  10:          Set(ByVal value As String)
  11:              Dim llistitem As ListItem
  12:              DropDownList1.ClearSelection()
  13:              For Each llistitem In DropDownList1.Items
  14:                  If RTrim(llistitem.Value) = RTrim(value) Then
  15:                      llistitem.Selected = True
  16:                      Exit For
  17:                  End If
  18:              Next
  19:          End Set
  20:      End Property
  22:  End Class

   1:  <asp:RequiredFieldValidator ID="rfvTask"
   2:         runat="server"
   3:         ErrorMessage="Task cannot be blank"
   4:         InitialValue=""
   5:         ControlToValidate="cboTask:DropDownList1"
   6:          ValidationGroup="page">*</asp:RequiredFieldValidator>

Doing this allows both client and server validation, and allows you to use the validation controls as you would with any of the existing .NET controls.