Friday, April 29, 2011

RequiredFieldvalidator

how to use required field validator for dropdownlist?.

my dropdown list having

-Day-

item1

item2

From stackoverflow
  • Use InitialValue property as the default item that you don't want to be selected :

    <asp:DropDownList ID="ddlItems" runat="server">
        <asp:ListItem Text="-Day-" Value="-Day-"></asp:ListItem>
        <asp:ListItem Text="Item 1" Value="Item 1"></asp:ListItem>
        <asp:ListItem Text="Item 2" Value="Item 2"></asp:ListItem>
    </asp:DropDownList>
    
    <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" 
        ErrorMessage="Validation Message !" ControlToValidate="ddlItems" 
        InitialValue="-Day-"></asp:RequiredFieldValidator>
    
    domus.vita : Cool, never knew about the InitialValue property. Thanks.
  • You could use a CompareValidator like this:

    <asp:DropDownList ID="ddlItems" runat="server">
        <asp:ListItem Text="-Day-" Value="-1"></asp:ListItem>
        <asp:ListItem Text="Item 1" Value="Item 1"></asp:ListItem>
        <asp:ListItem Text="Item 2" Value="Item 2"></asp:ListItem>
    </asp:DropDownList>
    
    <asp:CompareValidator runat="server" ID="CompareFieldValidator1" 
        ErrorMessage="Validation Message !" ControlToValidate="ddlItems" 
        ValueToCompare="-1" Operator="NotEqual"></asp:CompareValidator>
    

    -Edoode

0 comments:

Post a Comment