How to add a RequiredFieldValidator to DropDownList control?

前端 未结 4 804
青春惊慌失措
青春惊慌失措 2020-11-29 01:51

I have a DropDownList binded with aSqlDataSource to display the values from the database.

I am unable to validate using a RequiredFie

相关标签:
4条回答
  • 2020-11-29 02:12

    For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.

    <asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
    

    Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.

    If databinding you will need to insert the "Please select" value afterwards as follows

    this.ddl1.Items.Insert(0, "Please select");
    
    0 讨论(0)
  • 2020-11-29 02:13

    Suppose your drop down list is:

    <asp:DropDownList runat="server" id="ddl">
    <asp:ListItem Value="0" text="Select a Value">
    ....
    </asp:DropDownList>
    

    There are two ways:

    <asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />
    

    the 2nd way is to use a compare validator:

    <asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />
    
    0 讨论(0)
  • 2020-11-29 02:15

    If you are using a data source, here's another way to do it without code behind.

    Note the following key points:

    • The ListItem of Value="0" is on the source page, not added in code
    • The ListItem in the source will be overwritten if you don't include AppendDataBoundItems="true" in the DropDownList
    • InitialValue="0" tells the validator that this is the value that should fire that validator (as pointed out in other answers)

    Example:

    <asp:DropDownList ID="ddlType" runat="server" DataSourceID="sdsType"
                      DataValueField="ID" DataTextField="Name" AppendDataBoundItems="true">
        <asp:ListItem Value="0" Text="--Please Select--" Selected="True"></asp:ListItem>
    </asp:DropDownList>
    <asp:RequiredFieldValidator ID="rfvType" runat="server" ControlToValidate="ddlType" 
                                InitialValue="0" ErrorMessage="Type required"></asp:RequiredFieldValidator>
    <asp:SqlDataSource ID="sdsType" runat="server" 
                       ConnectionString='<%$ ConnectionStrings:TESTConnectionString %>'
                       SelectCommand="SELECT ID, Name FROM Type"></asp:SqlDataSource>
    
    0 讨论(0)
  • 2020-11-29 02:28

    InitialValue="0" : initial validation will fire when 0th index item is selected in ddl.

    <asp:RequiredFieldValidator InitialValue="0" Display="Dynamic" CssClass="error" runat="server" ID="your_id" ValidationGroup="validationgroup" ControlToValidate="your_dropdownlist_id" />
    
    0 讨论(0)
提交回复
热议问题