Dropdownlist validation in Asp.net Using Required field validator

前端 未结 4 532
终归单人心
终归单人心 2020-12-29 02:23

I have Dropdownlist whose value field and text field are bind at runtime. it has --select-- as first item with a value of 0 and the rest of the val

相关标签:
4条回答
  • 2020-12-29 02:52
    <asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic" 
        ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
        Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>
    
    0 讨论(0)
  • 2020-12-29 03:05

    I was struggling with this for a few days until I chanced on the issue when I had to build a new Dropdown. I had several DropDownList controls and attempted to get validation working with no luck. One was databound and the other was filled from the aspx page. I needed to drop the databound one and add a second manual list. In my case Validators failed if you built a dropdown like this and looked at any value (0 or -1) for either a required or compare validator:

    <asp:DropDownList ID="DDL_Reason" CssClass="inputDropDown" runat="server">
    <asp:ListItem>--Select--</asp:ListItem>                                                                                                
    <asp:ListItem>Expired</asp:ListItem>                                                                                                
    <asp:ListItem>Lost/Stolen</asp:ListItem>                                                                                                
    <asp:ListItem>Location Change</asp:ListItem>                                                                                            
    </asp:DropDownList>
    

    However adding the InitialValue like this worked instantly for a compare Validator.

    <asp:ListItem Text="-- Select --" Value="-1"></asp:ListItem>
    
    0 讨论(0)
  • 2020-12-29 03:12

    Add InitialValue="0" in Required field validator tag

     <asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID"
          Display="Dynamic" ValidationGroup="g1" runat="server"
          ControlToValidate="ControlID"
          InitialValue="0" ErrorMessage="ErrorMessage">
     </asp:RequiredFieldValidator>
    
    0 讨论(0)
  • 2020-12-29 03:16

    Here use asp:CompareValidator, and compare the value to "select" option.

    Use Operator="NotEqual" ValueToCompare="0" to prevent the user from submitting the "select".

    <asp:CompareValidator ControlToValidate="ddlReportType" ID="CompareValidator1"
        ValidationGroup="g1" CssClass="errormesg" ErrorMessage="Please select a type"
        runat="server" Display="Dynamic" 
        Operator="NotEqual" ValueToCompare="0" Type="Integer" />
    

    When you do above, if you select the "select " option from dropdown it will show the ErrorMessage.

    0 讨论(0)
提交回复
热议问题