具有下拉列表的ASP.Net自定义验证控件

5
以下代码用于使用自定义验证器验证DropDownList控件。
Default1.aspx
<td>
        <asp:DropDownList ID="DDL_Product" runat="server" Height="21px" Width="128px">
             <asp:ListItem>Select</asp:ListItem>
             <asp:ListItem>Nokia</asp:ListItem>
             <asp:ListItem>LG</asp:ListItem>
             <asp:ListItem>Samsung</asp:ListItem>
             <asp:ListItem>sony</asp:ListItem>
             <asp:ListItem>Micromax</asp:ListItem>
             <asp:ListItem>Karbonn</asp:ListItem>
             <asp:ListItem>Apple</asp:ListItem>
         </asp:DropDownList>
    </td>
    <td>
         <asp:CustomValidator ID="cv1" Display="Dynamic" ControlToValidate = "DDL_Product" OnServerValidate="ddl_server" runat="server" ForeColor="Red" ErrorMessage="Please Select the Product"></asp:CustomValidator>
    </td>

Default1.aspx.cs

protected void ddl_server(object sender, ServerValidateEventArgs e)
{
     if (e.Value.selectedIndex <= 0)
     {
        e.IsValid = true;
     }
     else
     {
        e.IsValid = false;
     }
}

上述验证未进行验证。 我不知道如何使用此控件并验证 DropDownList。请纠正错误。


你想要验证什么,是DropDownList是否有选定的值? - EmmanuelRC
如果索引值不能从0更改,或者其值不能从“Select”更改,则返回已翻译的文本为“是”。 - Hari
那么您不需要一个“CustomeValidator”,您需要的是一个“RequiredFieldValidator”。 - EmmanuelRC
3个回答

8

您应该使用 RequireValidator 进行此操作。

1) 添加 "Select" 项目的值,将被用于验证初始值:

<asp:DropDownList ID="DDL_Product" runat="server" Height="21px" Width="128px">
       <asp:ListItem Value="0">Select</asp:ListItem>
       /*Rest of items*/
</asp:DropDownList>

2) 然后像这样使用RequireValidator,将DDL中的初始值进行比较:

<asp:RequiredFieldValidator InitialValue="0" 
    ID="rfvDDL_Product" Display="Dynamic" 
    ControlToValidate="DDL_Product"
    runat="server"  Text="*" 
    ErrorMessage="Please Select the Product"
    ForeColor="Red">
</asp:RequiredFieldValidator>

编辑:

从MSDN解释:

CustomValidator 类

使用 CustomValidator 控件为输入控件提供用户定义的验证函数。CustomValidator 控件与其验证的输入控件是独立的,这使您可以控制在何处显示验证消息。

RequiredFieldValidator 类

使用此控件将输入控件设置为必填字段。如果输入控件的值在失去焦点时未从 InitialValue 属性更改,则输入控件无法通过验证。


非常感谢,它正在工作。我可以知道为什么在这里使用RequiredFieldValidator以及何时适用自定义验证器吗? - Hari

1
尝试在DropDownList中添加属性AutoPostBack="true"
<asp:DropDownList ID="DDL_Product" runat="server" Height="21px" Width="128px"
                  AutoPostBack="true">

如果只是为了验证值是否被选择,建议使用RequiredFieldValidator代替。


0
只需将ValidateEmptyText="true"添加到您的自定义验证器中,如下所示,以验证是否未选择任何内容:
<asp:CustomValidator ID="cv1" Display="Dynamic" 
                     ControlToValidate = "DDL_Product" 
                     OnServerValidate="ddl_server" 
                     runat="server" ForeColor="Red" 
                     ErrorMessage="Please Select the Product"
                     ValidateEmptyText="true">
</asp:CustomValidator>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接