Validation Controls
Validation Controls
ASP.NET validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don't get stored.
Client-side validation is good, but we must depend on browser and scripting language
support. The client-side validation is done in the user's browser using JavaScript and
another scripting. You can use client-side validation libraries such
as WebUIValidation.js in .NET.
Validation controls are an essential part of ASP.NET web development because they help
ensure the integrity of user input. When users enter information into web forms, there is always
the potential for intentional or unintentional errors. Validation controls provide a way to check
the accuracy and validity of user input before the web application processes it.
ASP.NET provides the following validation controls:
RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
Validator Description
CompareValidator It is used to compare the value of an input control against a value of another input control.
RangeValidator It evaluates the value of an input control to check the specified range.
RegularExpressionValidator It evaluates the value of an input control to determine whether it matches a pattern defined by a regular expression.
CustomValidator
ValidationSummar
BaseValidator Class
The validation control classes are inherited from the BaseValidator class hence they
inherit its properties and methods. Therefore, it would help to take a look at the
properties and the methods of this base class, which are common for all the validation
controls:
Members Description
SetFocusOnError It indicates whether in case of an invalid control, the focus should switch
to the related input control.
ValidationGroup The logical group of multiple validators, where this control belongs.
Validate() This method revalidates the control and updates the IsValid property.
RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not empty. It is
generally tied to a text box to force input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined
range.
It has three specific properties:
Properties Description
Type It defines the type of the data. The available values are: Currency, Date,
Double, Integer, and String.
</asp:RangeValidator>
CompareValidator Control
The CompareValidator control compares a value in one control with a fixed value or a
value in another control.
It has the following specific properties:
Properties Description
Operator It specifies the comparison operator, the available values are: Equal,
NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual,
and DataTypeCheck.
</asp:CompareValidator>
RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching against a
pattern of a regular expression. The regular expression is set in the
ValidationExpression property.
The following table summarizes the commonly used syntax constructs for regular
expressions:
\b Matches a backspace.
\t Matches a tab.
\ Escape character.
Apart from single character match, a class of characters could be specified that can be
matched, called the metacharacters.
Metacharacters Description
Quantifier Description
{N} N matches.
</asp:RegularExpressionValidator>
CustomValidator
The CustomValidator control allows writing application specific custom validation
routines for both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction property.
The client side validation routine should be written in a scripting language, such as
JavaScript or VBScript, which the browser can understand.
The server side validation routine must be called from the control's ServerValidate event
handler. The server side validation routine should be written in any .Net language, like
C# or VB.Net.
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>
ValidationSummary
The ValidationSummary control does not perform any validation but shows a summary
of all errors in the page. The summary displays the values of the ErrorMessage property
of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
ShowSummary : shows the error messages in specified format.
ShowMessageBox : shows the error messages in a separate window.
The syntax for the control is as given:
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />
Validation Groups
Complex pages have different groups of information provided in different panels. In
such situation, a need might arise for performing validation separately for separate
group. This kind of situation is handled using validation groups.
To create a validation group, you should put the input controls and the validation
controls into the same logical group by setting their ValidationGroup property.
It refers to managing the state of one or several user interface control systems like that of radio
controls, action buttons, input fields, etc. It is a programming technique for User Interface in
which the state of a single UI control completely or partially depends on the state of all the other
UI controls.
In an ASP NET application, state management in ASP NET is an object and preserves type state
control. This is because ASP NET applications are basically stateless. In ASP NET, the
information of users is stored and maintained till the user session ends. Each time the page is
posted on the server, a new instance of the Web page class is created. Whenever the user enters
information, this information might get lost in the round trip from the browser (MSDN), if they
enter into the web application.
Now, let’s discuss the types of State Management.
There are two types of State management in ASP net. They are :
Server-side
Client-side
Server-Side
Session
Application
Cache
Client-Side
Cookies
Viewstate
Control state
Query String
Hidden Field
Let us see in detail how these types of state management in ASP NET work -
Session
An important technique to maintain state. It is used to store identity and information; information
is stored in the server using Sessionid.
Example
Session["UserName"] = txtName.Text;
Response.Redirect("Home.aspx");
Session Event
Two types -
Session starts - Raised every time a new user requests without a session ID.
Example
Session["Master"] = "~/Master.master";
Session end - Raised everytime the user ends the session or a time out occurs.
Example
Response.Write("Session_End");
InProcMode - Default session mode. When the server starts, the session value is stored, and
when the server is restarted, it ends.
State Server Mode - Session date is made to store on a separate server in this mode.
SQL Server Mode - It’s a secure mode in which the session is made to store in the database.
Custom Mode - Session data is generally stored in InProcMode, SQL Server Mode, etc. In case
we want to store using any other techniques, we use the custom mode.
Application
It is a server-side management state and is also known as the application level state management.
This is mainly used to store user activity in server memory and application events.
Application start - The event begins with the start of the domain.
Example
Application error - This is used to manage/handle an error or exception that had been previously
unhandled.
Example
Example
Cache
This is stored on the server-side, and it is used to implement page caching and data caching. A
cache is primarily used to set expiration policies.
Example snippet
There are four main parts of State Management on the Client Side -
Cookie
One of the smallest but important parts of the ASP NET, it is used to store the session and
application information of the user. It can be constant and temporary and works with browser
requests. The server can read these cookies from the client-side and perform data abstraction.
Persistence - The Persistence cookie works along with Time and Date.
Example
Response.Cookies["CookiesName"].Value = "Testing Cookies";
Response.Cookies["CookiesName"].Expires = DateTime.Today.AddHours(2);
Non-Persistence - Temporary cookie created with application access and closed application is
discarded.
Example
Response.Cookies["CookiesName"].Value = "Testing Cookies";
Control State
It is a technique used to maintain data work in order, properly. We use Control State to use the
view state without the possibility of it being disabled by the user.
Example
if (!IsPostBack)
We use a customized control state to control the one being displayed when these two messages
are being displayed on the PostBack event.
Hidden Field
This field is used to store values on the client-side. The hidden field works on request and is not
displayed on the browser.
Example
if (HiddenField.Value != null)
HiddenField.Value = dat.ToString();
Labels.Text = dat.ToString();
Viewstate
It is used to manage page-level state and is used for storing, sending, and receiving information.
We can store small values in Viewstate, but it is pretty easy to apply since it does not require any
server resources. The page using Viewstate becomes heavy if more data is stored.
Example
if (ViewState["User_Name"] != null)
lblName.Text = ViewState["User_Name"].ToString();
Query String
Example
Response.Redirect("ShowStringValue.aspx?Username=" + txtUsername.Text);
Output
There are several custom session storage mechanisms that ASP.NET applications can use.
Custom session state store providers enable developers to create their own session state storage
mechanisms. This is the most flexible option, but also the most difficult to implement.
Developers can also use a custom session state manager. This option is less flexible than using a
custom session state store provider, but is easier to implement. Finally, developers can use a
custom session ID generator. This option is the simplest to implement, but provides the least
flexibility. Developers who want to use a custom session storage mechanism must first decide
which option is best for their needs.
State management is a process by which you maintain the state of an object or variable
throughout the lifetime of a page. In ASP.NET, there are two types of state management: client-
side state management and server-side state management.
Client-side state management refers to the technique of storing data on the client's browser in the
form of either cookies or hidden fields. Server-side state management, on the other hand, stores
data on the server in the form of either application state or session state.
Application state is a global storage mechanism that is used to store data that needs to be
available to all users of an ASP.NET application. Session state, on the other hand, is a per-user
storage mechanism that is used to store data that is specific to a user's session.
Cookies
One of the most common techniques for storing data on the client's browser is through the use of
cookies. Cookies are small text files that are stored on the user's computer, and they can be used
to store data such as user preferences, session information, and so on.
To create a cookie, you can use the Response.Cookies collection, as shown below:
Response.Cookies["userName"].Value = "John Smith";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
In the code above, we are creating a cookie named "userName" and setting its value to "John
Smith". We are also setting an expiration date for the cookie, so that it will be deleted from the
user's computer after one day.
To retrieve a cookie, you can use the Request.Cookies collection, as shown below:
If you want to delete a cookie, you can set its value to an empty string and then expire it
immediately, as shown below:
Response.Cookies["userName"].Value = "";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(-1);
Hidden Fields
Another technique for storing data on the client's browser is through the use of hidden fields.
Hidden fields are HTML input elements that are used to store data that is not meant to be seen or
edited by the user.
To retrieve the value of a hidden field, you can use the Request.Form collection, as shown
below:
ViewState
ViewState is a technique that is used to store the state of a page between postbacks. ViewState is
stored in a hidden field on the page, and it is encoded using base64 encoding.
ViewState can be used to store data such as user input, control state, and so on. To enable
ViewState for a page, you can use the following code:
To access the ViewState of a page, you can use the following code:
To store data in the ViewState of a page, you can use the following code:
Application State
Application state is a global storage mechanism that is used to store data that needs to be
available to all users of an ASP.NET application. Application state is stored in memory on the
server, and it is specific to an ASP.NET application.
To access the application state, you can use the following code:
To store data in the application state, you can use the following code:
Session State
Session state is a per-user storage mechanism that is used to store data that is specific to a user's
session. Session state is stored in memory on the server, and it is specific to a user's session.
To access the session state, you can use the following code:
To store data in the session state, you can use the following code:
Session["userName"] = "John Smith";
Profile Properties
Profile properties are a per-user storage mechanism that is used to store data that is specific to a
user's profile. Profile properties are stored in a database, and they can be used to store data such
as user preferences, contact information, and so on.
To store a value in a profile property, you can use the following code:
Cache
The cache is a global storage mechanism that is used to store data that needs to be available to all
users of an ASP.NET application. The cache is stored in memory on the server, and it is specific
to an ASP.NET application.
To store data in the cache, you can use the following code:
Conclusion
Statement Management in ASP NET is an important part of the complete web application
development process using ASP NET. It is used to help us manage the state of one or several