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".
<ValidationPropertyAttribute("value")> _
Partial Public Class ctlDropDownList
Inherits System.Web.UI.UserControl
Public Property value() As String
Get
Return DropDownList1.SelectedValue.Trim()
End Get
Set(ByVal value As String)
Dim llistitem As ListItem
DropDownList1.ClearSelection()
For Each llistitem In DropDownList1.Items
If RTrim(llistitem.Value) = RTrim(value) Then
llistitem.Selected = True
Exit For
End If
Next
End Set
End Property
End Class
<asp:RequiredFieldValidator ID="rfvTask"
runat="server"
ErrorMessage="Task cannot be blank"
InitialValue=""
ControlToValidate="cboTask:DropDownList1"
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.
Subscribe to:
Posts (Atom)