0% found this document useful (0 votes)
101 views

Validation Controls

ASP.NET validation controls validate user input on both the client-side and server-side. There are two main types - client-side controls perform validation in the user's browser using JavaScript while server-side controls validate on the server using C#. Common validation controls include RequiredFieldValidator, RangeValidator, CompareValidator, and RegularExpressionValidator. ValidationSummary displays a list of all validation errors on the page.

Uploaded by

Amandeep Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Validation Controls

ASP.NET validation controls validate user input on both the client-side and server-side. There are two main types - client-side controls perform validation in the user's browser using JavaScript while server-side controls validate on the server using C#. Common validation controls include RequiredFieldValidator, RangeValidator, CompareValidator, and RegularExpressionValidator. ValidationSummary displays a list of all validation errors on the page.

Uploaded by

Amandeep Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

validation controls

ASP.NET validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don't get stored.

ASP.NET supports two types of validation controls:

1. Client-side validation controls


2. Server-side validation controls

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.

Server-side validation in ASP.NET is done in the C# code-behind, where the value of


the user input is read and validated on the server. This process is time-consuming but
provides better security and is easier to implement in ASP.NET. For example, if an app
wants to check the date range, the date value will be read from ASP.NET in C#, and the
C# code behind the validation method will be compared against the rules.

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.

RequiredFieldValidator It is used to make a control required.

ValidationSummary It displays a list of all validation errors on the Web page.

 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

ControlToValidate Indicates the input control to validate.

Display Indicates how the error message is shown.

EnableClientScript Indicates whether client side validation will take.

Enabled Enables or disables the validator.

ErrorMessage Indicates error string.

Text Error text to be shown if validation fails.

IsValid Indicates whether the value of the control is valid.

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.

MinimumValue It specifies the minimum value of the range.

MaximumValue It specifies the maximum value of the range.

The syntax of the control is as given:


<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">

</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

Type It specifies the data type.

ControlToCompare It specifies the value of the input control to compare with.

ValueToCompare It specifies the constant value to compare with.

Operator It specifies the comparison operator, the available values are: Equal,
NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual,
and DataTypeCheck.

The basic syntax of the control is as follows:


<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="CompareValidator">

</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:

Character Escapes Description

\b Matches a backspace.

\t Matches a tab.

\r Matches a carriage return.

\v Matches a vertical tab.

\f Matches a form feed.

\n Matches a new line.

\ Escape character.

Apart from single character match, a class of characters could be specified that can be
matched, called the metacharacters.

Metacharacters Description

. Matches any character except \n.

[abcd] Matches any character in the set.

[^abcd] Excludes any character in the set.

[2-7a-mA-M] Matches any character specified in the range.

\w Matches any alphanumeric character and underscore.

\W Matches any non-word character.

\s Matches whitespace characters like, space, tab, new line etc.

\S Matches any non-whitespace character.

\d Matches any decimal character.


\D Matches any non-decimal character.

Quantifiers could be added to specify number of times a character could appear.

Quantifier Description

* Zero or more matches.

+ One or more matches.

? Zero or one matches.

{N} N matches.

{N,} N or more matches.

{N,M} Between N and M matches.

The syntax of the control is as given:


<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"
ValidationExpression="string" ValidationGroup="string">

</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.

State Management in General Terms

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.

Also Read: How to Learn Programming?

State Management in ASP.NET

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.

Types of State Management in ASP.NET

There are two types of State management in ASP net. They are :

 Server-side

 Client-side

These are further subdivided into the following -

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 -

Become a Skilled Web Developer in Just 9 Months!

Caltech PGP Full Stack DevelopmentEXPLORE PROGRAM


State Management in ASP.NET Techniques

Server-Side of State Management in ASP NET

Session

An important technique to maintain state. It is used to store identity and information; information
is stored in the server using Sessionid.

To start the user session -

Example

protected void btnSubmit_Click(object sender, EventArgs e)

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

void Session_Start(object sender, EventArgs e)

Session["Master"] = "~/Master.master";

Session end - Raised everytime the user ends the session or a time out occurs.
Example

void Session_End(object sender, EventArgs e)

Response.Write("Session_End");

The session is stored in the following ways in ASP.NET:

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.

This is further classified into three types :

Application start - The event begins with the start of the domain.

Example

Void ApplicationStart(object sender, EventArgs e)

Application["ApplicationstartMessage"] = "Welcome to Simplilearn";


}

Application error - This is used to manage/handle an error or exception that had been previously
unhandled.

Example

void ApplicationError(object sender, EventArgs e)

// Unhandled exception code block

Application end - Whenever the domain ends, this ends as well.

Example

Void ApplicationEnd(object sender, EventArgs e)

Application["ApplicationEndMessage"] = "Applications are Closed";

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.

Client-Side State Management in ASP.NET

There are two types of cookies that are available -

Persistence - The Persistence cookie works along with Time and Date.

Example
Response.Cookies["CookiesName"].Value = "Testing Cookies";

//setting the expire time

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)

lblmsg1.Text = "Welcome to Simplilearn!";

lblmsg2.Text = "Welcome to Simplilearn!";


}

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)

int dat = Convert.ToInt32(HiddenField.Value) + 1;

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

The query string is used to store the value in the URL.

Example
Response.Redirect("ShowStringValue.aspx?Username=" + txtUsername.Text);
Output

Custom Session Mode

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.

Sample Code and Examples

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.

Client-Side State Management

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:

string userName = Request.Cookies["userName"].Value;

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 create a hidden field, you can use the following code:

<input type="hidden" name="userName" value="John Smith" />

To retrieve the value of a hidden field, you can use the Request.Form collection, as shown
below:

string userName = Request.Form["userName"];

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:

<%@ Page EnableViewState="true" %>

To access the ViewState of a page, you can use the following code:

string viewState = (string)ViewState["userName"];

To store data in the ViewState of a page, you can use the following code:

ViewState["userName"] = "John Smith";

Server-Side State Management

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:

string appState = (string)Application["userName"];

To store data in the application state, you can use the following code:

Application["userName"] = "John Smith";

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:

string sessionState = (string)Session["userName"];

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 access a profile property, you can use the following code:

string profileProperty = (string)Profile["userName"];

To store a value in a profile property, you can use the following code:

Profile["userName"] = "John Smith";

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 access the cache, you can use the following code:

string cacheItem = (string)Cache["userName"];

To store data in the cache, you can use the following code:

Cache["userName"] = "John Smith";

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

You might also like