A couple of days ago, I faced a situation whereby I needed to add some form validation to an aspx page.

I had options of either JavaScript or ASP.net client side validation. JavaScript seemed like an easier solution…
<h5>Client-side JavaScript for form validation</h5>

<script language="javascript">
Function CheckForm(form)
 for(var intCtr = 0; intCtr <= (form.elements.length - 5); ++intCtr)
 var temp = form.elements[intCtr];
 if(temp.type == "text" && temp.value == "")
 alert("Please Enter All Information!");
 return false;
 return true;

All good and well with the above, however the code above doesn’t check for all the information that you might need on the form you are building. This piece of code determines only whether the user entered anything at all in all five fields within the form. It does not determine whether the user entered an actual e-mail address within the e-mail address text box, whether the user entered a number between two given numbers, or whether the password and the confirm password text boxes match. After awhile, you can see that you need many JavaScript functions to obtain the level of form validation required.
<h5>ASP.net Client-side validation</h5>

<%@ Page Language="C#" %>
<script runat="server">

void Button1_Click(Object sender, EventArgs e) {
 Label1.Text = "Page is valid!";

 <form runat="server">
 <asp:TextBox id="TextBox1"
 id="RequiredFieldValidator1" runat="server"
 <asp:Button id="Button1" onclick="Button1_Click"
 runat="server" Text="Button"></asp:Button>
 <asp:Label id="Label1" runat="server"></asp:Label>

<strong>Causing the RequiredFieldValidator server control to fire</strong>

There are a few things to be aware of when using the RequiredFieldValidator server control in your ASP.NET pages. First of all, the most important property of this validation control is the ControlToValidate property. The value assigned to this control needs to be the value of the id property for the control to which you want to link the RequiredFieldValidator control. You can link only one RequiredFieldValidator server control to any other server control on the page. For instance, if you have three required TextBox controls on your ASP.NET page, you need three separate RequiredFieldValidator controls to make sure that they are all required.


The second property of this control is the ErrorMessage property. This is the text that appears where the RequiredFieldValidator control is located on the ASP.NET page if the TextBox is left empty. Instead of using the ErrorMessage property, you can also use the Text property:

<asp:RequiredFieldValidator id="RequiredFieldValidator1"
 runat="server" Text="Required!"

Presently, six different validation server controls are available for ASP.NET:


The “RequiredFieldValidator” was the common one used in my situation and turned out to be pretty helpful.