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>




cover image of azure cloud book

Develop Azure Applications

Azure Cloud is gaining popularity and is competing with Amazon Elastic Cloud and Google Cloud for a spot in the billion dollar Cloud computing space.

With this book learn how to use - Table (an Azure Table is different from a SQL Server Table), Queue, Blob storage services, use your local machine to create an Application and a Service, how Azure splits a Table to achieve Load Balancing, Scalability based on the Partition Key, AppFabric Service Bus, Access Control Service, role of Fabric Controller, features of Azure SQL Database and Content Delivery Network.

Many have mastered Cloud Programming and are enjoying the benefits. Why not you?

View Highlights » View Contents »
cover image of foundation database programming book

Create your Own Accounting Software

A foundation book to Master Accounting Software Development, VB.Net, C# and OOPs programming. Detailed explanation of the Accounting domain for programmers is included. SQL and ADO.Net is also covered in detail.

This book gives you a strong foundation in Application Development.

A thorough understanding of the contents will enable you to grasp the topics covered in the accompanying books quite easily. This is because, the accounting domain is dealt with great detail in this book.

The ideal book to get started with application development in the .Net world.

View Highlights » View Contents »

cover image of asp.net book

Create your Own WEB ERP Software using ASP.Net

This book opens you to the Web. Using ASP.Net, C# and SQL Server as the tools, you will learn to build a Multi Tier Web Application as recommended by Microsoft. You will learn implementing inline GridView control, Transaction Management for a layered Web Application, build Data Access component and a Business Layer component.

Opens you to a world of opportunities. You will be able to develop a Web ERP application including all the five modules and learn how to use the TreeView control and GridView control to implement transactions such as Purchase Invoice, Sales Order and Sales Invoice.

View Highlights » View Contents »
cover image of entity framework book

ASP.Net MVC 5 Application Development Using Entity Framework 6 and VS 2015

Entity frameworks is the latest buzz in .Net programming and is the data access technology for Microsoft OS based hand held devices and web applications. Learn to integrate EF into an ASP.Net Application and MVC application. Create, explore and query the Entity Data Model. Learn how to use ObjectDataSource control and GridView control in an ASP.Net Application.

Also, learn to build Three-Tier ASP.Net application, create a business-class, implement methods in the class to perform CRUD operations and bind a GridView to the ObjectDataSource control. Learn how to handle concurrency and managing Transactions.

View Contents »