我们如何在aspx页面中的用户控件上使用必需的字段验证器

Him*_*shu 4 .net asp.net user-controls

我们如何在aspx页面中的用户控件上使用必需的字段验证器?

我有一个用户控件有一个下拉.我在我的页面上使用此控件.我想在此下拉列表中使用必填字段验证程序.

我该怎么用?

m.e*_*son 7

这是我自己的答案在这里.

要允许自定义用户控件进行验证,首先需要添加的是<ValidationPropertyAttribute("value")>.这指定了提供要验证的字符串的属性,其中"value"是属性的名称.

其次,ControlToValidate=""页面上验证控件的属性应该是用户控件的ID,冒号(:),然后是与'value'关联的控件的ID.

例如,我有一个名为cboTask的控件,<ValidationPropertyAttribute("value")>它在其中定义了value是一个属性,它返回了包含在cboTask中的DropDownList(DropDownList1)的当前值.为了验证用户选择了一个选项,我使用了RequiredFieldValidator 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
Run Code Online (Sandbox Code Playgroud)

<asp:RequiredFieldValidator ID="rfvTask"
       runat="server"
       ErrorMessage="Task cannot be blank"
       InitialValue=""
       ControlToValidate="cboTask:DropDownList1"
        ValidationGroup="page">*</asp:RequiredFieldValidator>
Run Code Online (Sandbox Code Playgroud)