16 September, 2010

Complete use of RequiredFieldValidator

It's very common to use asp:RequiredFieldValidator to validate form data before submission. Using this for a TextBox is very straight forward, but Today, I came to know that the same can be used effectively to validate asp:DropDownList and asp:RadioButtonsList too. Lets know, how this can be done.

First of all, the usage depends on the Binding of List Items. If all the Items are static and added with <asp:ListItem> as below

<asp:DropDownList ID="ddlAddress" Width="150" runat="server">

Here first item is optional and used for DropDownList in general. Now, the RequiredFieldValidator for this dropdownlist will be as following:
<asp:RequiredFieldValidator ID="rfvaAddress" InitialValue="0" ControlToValidate="ddlAddress" runat="server" ErrorMessage="*" CssClass="Note" />
Here InitialValue is an optional property which is used to mention the Item, which should be selected by default.

But in general the dropdowns are binded in code-behind. If we have an initial item with select text, the value for that select item should be string.Empty. If you don't have this default item, the first item will be selected by default and there is no use of RequiredFieldValidator.

No comments:

Post a Comment