To render a TextBox,DropDownList , ListBox as a mandatory field for the end user to input data before a form can be submitted to the server, we can follow this approach.
Validations
Validation controls are used to validate the input in the the form fields for validating data when it is to be submitted to the server.
Get 500+ ASP.NET web development Tips & Tricks and ASP.NET Online training here.
ASP.NET provides 5 validation types (and controls) out of the box. They are
1. RequiredFieldValidator
2. RangeValidator
3. CompareValidator
4. RegularExpressionValidator and
5. CustomValidator
A related control i.e ValidationSummary doesn't participate in validation but used alongwith other validation controls to display the error messages from all other controls, together as a summary.
In the previous article, we learnt about How to render ordered list or un-ordered list (bulleted) using Repeater control? In this article, we shall learn how validate a TextBox, DropDownList / ListBox as a mandatory field?
To make a TextBox as mandatory we can follow this approach.
ASPX PAGE
Username: <asp:TextBox ID="txtUserName" runat="server" />
<asp:RequiredFieldValidator ID="req1" runat="server" ErrorMessage="Mandatory!" ForeColor="Red" ControlToValidate="txtUserName" />
<p><asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="SubmitData" /></p>
CODE BEHIND
protected void SubmitData(object sender, EventArgs e)
{
}
In the above code snippet, we have a TextBox and a Button. As we want to validate the textbox as a mandatory field so we have used asp:RequiredFieldValidator with ErrorMessage that we want to display if the validation fails and ControlToValidate property set to the TextBox (in this case txtUserName) that should be validated.
OUTPUT

To make a DropDownList or ListBox as a mandatory field we can follow this approach.
ASPX PAGE
Select age: <asp:DropDownList ID="dropDownAge" runat="server">
<asp:ListItem Text="Select Age" Value="0" />
<asp:ListItem Text="18" Value="18" />
<asp:ListItem Text="19" Value="19" />
<asp:ListItem Text="20" Value="20" />
<asp:ListItem Text="> 20" Value=">20" />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqAge" runat="server" ErrorMessage="Please
select age" ForeColor="Red"
ControlToValidate="dropDownAge" InitialValue="0" />
<p><asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="SubmitData" /></p>
CODE BEHIND
protected void SubmitData(object sender, EventArgs e)
{
}
In the above code snippet, the first item of the DropDownList is “Select Age” with value as “0”; we want the user to select any age. To do that we can specifiy the RequiredFieldValidator InitialValue as “0”, this will cause the RequiredFieldValidator fail unless user select any age other than “0” from the DropDownList.
OUTPUT

Note: In the same fashion, we can perform ListBox validation too.
Hope this article was useful. Thanks for reading.
Keep reading my forth coming articles. To read my series of articles on ASP.NET,click here.