How to implement form validation using ASP.Net 2.0 Validation Controls in a Web Application


Before saving the data entered by the user into a webform, we will have to validate the data. A web form is form which is used to accept data from the user in a web application. In this article, we will see how to use the validation controls in a webform to perform the validations against the data entered by the user. Validation controls are controls which help us to perform different validations on the data entered in controls like Textbox, Listbox and radiobutton.
working of validation controls in an ASP.Net page

What are the different validation controls available in Asp.net? Which validation control do you use for a particular validation? For answers to these questions, read Develop your own Web Accounting Application Using ASP .Net 2.0

Using validation controls, we can perform the following validations.

We need to check whether user has entered data in a field because the value which is entered into this field is going to be stored in a field which cannot be NULL. Even though, we can check this validation using a stored procedure on the Database server side, it is always better to use validation controls to avoid round trips.

Whether user has entered data which is valid. Common entries are email Ids, telephone numbers, URLs and credit card numbers.

We can add validation controls to a webform just like any other controls. For each specific type of validation, there is s specific validation control available in the .Net framework. The common validation controls we use in a webform are:
  • RequiredFieldValidator Control - For compulsory required fields
  • RegularExpressionValidator Control - For Validating expressions
  • CompareValidator Control - For Comparing values
  • RangeValidator control - For checking of a range of values
  • ValidationSummary control - For Summarizing Validation Errors

How to use RequiredFieldValidator Control in Visual Basic 2005


The RequiredFieldValidator Control checks whether the user has entered any data in a field. The important properties of the RequiredFieldValidator Control are:

Text : Sets the error message displayed by the control.
ControlToValidate : Specifies the ID of the control that you want to validate.
IsValid : Has the value True when the validation succeeds.

In the following example, using of validation controls is shown for a form which has two textbox controls and one button. We will add RequiredFieldValidator controls for both the text box controls. In this example, if the user presses the button without entering data in both the fields, an error occurs.


When the the form is submitted and the user's input is processed, the framework transmits the data entered in a control to the associated validation control. The validation control tests the data and sets the IsValid property to indicate whether the data qualifies to be passed. After all validation tests in a form have been passed, the IsValid property on the page is set. If any of the validation fails, the entire page is set to invalid.
<html>
<head>
<title>Untitled Page</title>
<script language="VB" runat="server">
Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
If (Page.IsValid) Then
lblError.Text = "Page is Valid!"
Else
lblError.Text = "The fields are empty"
End If
End Sub
</script>
</head>
<body>

<form id="form1" runat="server">
<b>Username:</b>
<br/>
<asp:TextBox ID="txtUsername" runat="Server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="txtUsername"
Text="Required!"
runat="Server" />
<br />

<asp:Label
ID="lblError"
EnableViewState="False"
runat="Server" />

<b>Password:</b>
<br/>
<asp:TextBox
ID="txtPassword"
TextMode="password"
runat="Server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
ControlToValidate="txtPassword"
Text="Required!"
runat="Server" />
<br />

<asp:Button ID="Button1"
Text="Login!"
OnClick="Button_Click"
runat="Server" />

</form>
</body>
</html>

How to use RequiredFieldValidator Control C#

<html>
<head runat="server">
<title>Untitled Page</title>
<script language="C#" runat="server">

void Button_Click(Object Sender, EventArgs e)
{ 
if (Page.IsValid == true) 
{ 
lblError.Text = "Page is Valid!";
} 
else 
{ 
lblError.Text = "The fields are empty";
} 
} 
</script>

</head>
<body>

<form id="form1" runat="server">

<b>Username:</b>
<asp:TextBox ID="txtUsername" runat="Server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="txtUsername"
Text="Required!"
runat="Server" />

<asp:Label
ID="lblError"
EnableViewState="False"
runat="Server" />

<b>Password:</b>
<asp:TextBox
ID="txtPassword"
TextMode="password"
runat="Server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
ControlToValidate="txtPassword"
Text="Required!"
runat="Server" />

<asp:Button ID="Button1"
Text="Login!"
OnClick="Button_Click"
runat="Server" />

</form>
</body>
</html>

In the Button_Click subroutine, we are actually checking the Page using the statement "Page.IsValid == true" because the property IsValid is true only if the Isvalid property of every control is true. We can wire the validation control to any control by using the property ControlToValidate.

How to use RegularExpressionValidator Control in Csharp 2005

The RegularExpressionValidator Control checks the data entered by the user matches a pattern defined by a regular expression.

The important property of the RegularExpressionValidator Control is :

ValidationExpression : The regular expression defines a pattern that the input data must match to be valid.

In this exercise, we will see how we can Validate Email ID and Web site URL using RegularExpressionValidator Control

<html>
<head>
<title>Untitled Page</title>
<script language="C#" runat="server">

void Button_Click(Object Src, EventArgs e)
{

if (Page.IsValid) {
lblError.Text = "Page is Valid!";
}
else {
lblError.Text = "Page is InValid!" ;
}
}

</script>
</head>

<body>
<form id="form1" runat="server">
<div>

<asp:Label id="lblEmail" 
Text="Email ID" runat="server" />

<asp:TextBox ID="txtEmail" 
MaxLength="50" runat="server" /> 
<asp:RequiredFieldValidator ID="txtEmailValidator" 
ControlToValidate="txtEmail" 
Text="*" ErrorMessage="Email is Missing" 
runat="server" /> 

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" 
ControlToValidate="txtEmail" 
Text="Invalid Email Address" 
ValidationExpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9] 
{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" runat="server" />


<asp:Label
ID="lblError"
EnableViewState="False"
runat="Server" />

<asp:Label id="lblWebsite" 
Text="Website" runat="server" />

<asp:TextBox ID="txtWebsite" 
MaxLength="100" runat="server" /> 

<asp:RequiredFieldValidator ID="txtWebsiteValidator" 
ControlToValidate="txtWebsite" 
Text="*" 
ErrorMessage="Website is Missing" runat="server" />
<asp:RegularExpressionValidator 
ID="RegularExpressionValidator2" 
ControlToValidate="txtWebsite" 
Text="Invalid URL" 
ValidationExpression="http://\S+\.\S+" runat="server" />

<asp:Button ID="Button1"
Text="Add!"
OnClick="Button_Click"
runat="Server" />

</div>
</form>
</body>
</html>


The following sample shows how to use the control ib Visual Basic 2005

<html>
<head runat="server">
<title>Untitled Page</title>
<script language="VB" runat="server">
Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
If (Page.IsValid) Then
lblError.Text = "Page is Valid!"
Else
lblError.Text = "The fields are empty"
End If
End Sub
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label id="lblEmail" 
Text="Email ID" runat="server" />

<asp:TextBox ID="txtEmail" 
MaxLength="50" runat="server" /> 
<asp:RequiredFieldValidator ID="txtEmailValidator" 
ControlToValidate="txtEmail" 
Text="*" ErrorMessage="Email is Missing" 
runat="server" /> 

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" 
ControlToValidate="txtEmail" 
Text="Invalid Email Address" 
ValidationExpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)
|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" runat="server" />


<asp:Label
ID="lblError" runat="Server" />

<asp:Label id="lblWebsite" 
Text="Website" runat="server" />

<asp:TextBox ID="txtWebsite" 
MaxLength="100" runat="server" /> 

<asp:RequiredFieldValidator ID="txtWebsiteValidator" 
ControlToValidate="txtWebsite" 
Text="*" 
ErrorMessage="Website is Missing" runat="server" />
<asp:RegularExpressionValidator 
ID="RegularExpressionValidator2" 
ControlToValidate="txtWebsite" 
Text="Invalid URL" 
ValidationExpression="http://\S+\.\S+" runat="server" />

<asp:Button ID="Button1"
Text="Add!"
OnClick="Button_Click"
runat="Server" />

</div>
</form>
</body>
</html>