ASP.Net Custom Validator with DropDownList

The following code is used to test DropDownList control using Custom Validator.

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; } } 

The above verification is not performed. I do not know how to use this control and check DropDownList. Correct the mistake.

+4
source share
2 answers

For this you must use the RequireValidator.

1) Add a value for the Select element, which will be used to check the original value:

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

2) Then use the RequireValidator as follows, comparing the initial value with 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> 

EDIT:

For explanation, from MSDN:

CustomValidator Class

Use the CustomValidator control to provide custom validation for input control. The CustomValidator control is a separate control from the input control, which it validates, which allows you to control where the validation message is displayed.

Class RequiredFieldValidator

Use this control to make input control a required field. Input control fails the test if its value does not change from the InitialValue property after losing focus.

+7
source

Try adding the AutoPostBack="true" property to the DropDownList .

 <asp:DropDownList ID="DDL_Product" runat="server" Height="21px" Width="128px" AutoPostBack="true"> 

and also if you only need to check if a value has been selected, use RequiredFieldValidator instead.

+1
source

Source: https://habr.com/ru/post/1491437/


All Articles