RequiredFieldValidator is the simplest available control in ASP.NET. You can use it to ensure that the associated control is not empty. For example, the control will fail validation if a linked text box doesn’t contain any content or contains spaces. Instead of checking for blank values you can specify a default value using the InitialValue property. In this case, validation fails if the content in the control matches this InitialValue (indicating that the user hasn’t changed it in any way).
The next code lines shows typical usage of the RequiredFieldValidator:
<asp:TextBox runat=”server” ID=”Name” />
<asp:RequiredFieldValidator runat=”server”
ControlToValidate=”FirstName” ErrorMessage=”First Name is required”
Display=”dynamic”>*
</asp:RequiredFieldValidator>
The validator declared here will show an asterisk (*) character if the FirstName text box is empty. This error text appears when the user tries to submit the form by clicking a button that has CausesValidation set to true. It also occurs on the client side in Internet Explorer 5.0 or above as soon as the user tabs to a new control, thanks to the client-side JavaScript.
If you want to place a specific message next to the validated control, you should replace * with an error message. You don’t need to use the ErrorMessage property. The ErrorMessage is required only if you want to show the summary of all the errors on the page using the ValidationSummary control. For a nicer result, you could use an HTML <img> tag to use a picture (such as the common ! sign inside a yellow triangle with a tooltip for the error message.
<asp:TextBox runat=”server” ID=”Name” />
<asp:RequiredFieldValidator runat=”server”
ControlToValidate=”FirstName” ErrorMessage=”First Name is required”
Display=”dynamic”>
<img src=”imgError.gif” alt=” First Name is required” />
</asp:RequiredFieldValidator>