User input validation is an important component in any user interface. In the realm of web development a response UI is extremely important to the users experience.
Take for example a simple drop down control.
<asp:DropDownList ID="ddlSampleDropDown" runat="server"> <asp:ListItem Value="">--please select one--</asp:ListItem> <asp:ListItem Value="1">Apples</asp:ListItem> <asp:ListItem Value="2">oranges</asp:ListItem> </asp:DropDownList>
In our scenario we do not want to pre-select a choice for the user, but we do want the user to have to make a choice. Instead of posting the form back to the server to validate the drop down, we can make use of the Required Field Validator control.
The Required Field Validator is an ASP.NET control that prevents the form from posting back until another control has been modified from its initial value.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ddlSampleDropDown" InitialValue="" ErrorMessage="Please make a choice">
The important parts of the validator are the ControlToValidate, InitialValue, and ErrorMessage properties.
The ControlToValidate is the ASP.NET control id that we need to validate, so in our example the id of the drop down. The InitialValue for our example is the value of the ListItem of our drop down that represents the unselected status. And finally the ErrorMessage property contains literal text to be displayed to your site visitor if they do not select a valid value before attempting to post the form.
The RequiredFieldValidator control does not remove the need for server side validation of form input, it just lessons the burden of providing responsive error messages.