0% found this document useful (0 votes)
49 views8 pages

Unit 2

The document discusses different types of validation including server-side validation, client-side validation, and various ASP.NET validation controls like RequiredFieldValidator, RangeValidator, CompareValidator, RegularExpressionValidator, and CustomValidator. It also covers the ValidationSummary control.

Uploaded by

hbbaleja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views8 pages

Unit 2

The document discusses different types of validation including server-side validation, client-side validation, and various ASP.NET validation controls like RequiredFieldValidator, RangeValidator, CompareValidator, RegularExpressionValidator, and CustomValidator. It also covers the ValidationSummary control.

Uploaded by

hbbaleja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

UNIT II

What is Validation?
Assessment of an action, decision, plan, or transaction to establish that it is (1) correct, (2)
complete, (3) being implemented (and/or recorded) as intended, and (4) delivering the intended
outcome.
Validations can be performed on the server side or on the client side (web browser). The user input
validation take place on the Server Side during a post back session is called Server-Side Validation
and the user input validation take place on the Client Side (web browser) is called Client-Side
Validation. Client-Side Validation does not require a postback. If the user request requires server
resources to validate the user input, you should use Server-Side Validation. If the user request does
not require any server resources to validate the input, you can use Client-Side Validation.

Server-Side Validation
In the Server-Side Validation, the input submitted by the user is being sent to the server and
validated using one of server-side scripting languages such as ASP.Net, PHP etc. After the
validation process on the Server Side, the feedback is sent back to the client by a new dynamically
generated web page. It is better to validate user input on Server Side because you can protect
against the malicious users, who can easily bypass your Client-Side scripting language and
submit dangerous input to the server.

Client-Side Validation
In the Client-Side Validation, you can provide a better user experience by responding quickly at
the browser level. When you perform a Client-Side Validation, all the user inputs validated in the
user's browser itself. Client-Side validation does not require a round trip to the server, so the
network traffic which will help your server perform better. This type of validation is done on the
browser side using script languages such as JavaScript, VBScript or HTML5 attributes.

Mostly the Client-Side Validation depends on the JavaScript Language, so if users turn JavaScript
off, it can easily bypass and submit dangerous input to the server. So the Client Side Validation
cannot protect your application from malicious attacks on your server resources and databases.

As both the validation methods have their own significances, it is recommended that the Server-
side validation is more SECURE!

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

ASP.NET provides the following validation controls:


1. RequiredFieldValidator
2. RangeValidator
3. CompareValidator
4. RegularExpressionValidator
5. CustomValidator
6. ValidationSummary

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
jquery, 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:" />
Difference between Exception and Error
System.Exception class is the base class for all exceptions. Exceptions provide a structured,
uniform, and type-safe way of controlling both system level and application level abnormal
conditions. It can be generated by system or can be generated programmatically.
An exception is an Object of a type deriving from the System.Exception class. SystemException
is thrown by the CLR (Common Language Runtime) when errors occur that are non-fatal and
recoverable by user programs. It is meant to give an opportunity to do something with throw
statement to transfer control to a catch clause in a try block.

Handling Exception:
try

{
//write your code here
}
Catch (exception type)
{
//write your code here or use throw statement
}

An Error is something that cannot be handle. Errors are unchecked exception, and the developer
is not required to do anything with these. Errors normally tend to signal the end of program; it
typically cannot be recovered from and cause exit from current program. It may not be caught or
handled.

All the Errors are Exceptions, but the reverse is not true. In general Errors are which nobody can
control or guess when it happened, on the other hand Exception can be guessed and can be handled.

Exception Handling
Exceptions are the occurrence of some condition that changes the normal flow of execution. In
.NET languages, Structured Exceptions handling is a fundamental part of Common Language
Runtime.

C# Exception handling
The C# language uses exceptions to handle errors and other exceptional events. Exceptions are the
occurrence of some conditions that changes the normal flow of execution . Exceptions are occurred
in situations like your program run out of the memory , file does not exist in the given path ,
network connections are dropped etc. More specifically for better understanding , we can say it as
Runtime Errors occurs during the execution of a program that disrupts the normal flow of
instructions
C# exception
In .NET languages, Structured Exceptions handling is a fundamental part of Common Language
Runtime. All exceptions in the Common Language Runtime are derived from a single base class,
also you can create your own custom exception classes. You can create an exception class that
inherits from Exception class. Creating an exception object and handing it to the runtime system
is called throwing an exception.
C# Exception Handling - try-catch
C# Exception handling uses the try, catch, and finally keywords to attempt actions that may not
succeed, to handle failures, and to clean up resources afterwards.
try
{
//your code here
}
Catch (exception type)
{
//your code here
}

finally
The code in the finally block will execute even if there is no Exceptions. That means if you write
a finally block, the code should execute after the execution of try block or catch block.
try
{
//your code here
}
Catch (exception type)
{
//if the exception occurred
//your code here
}
finally
{
//your code here
}

The following example trying to divide a number by zero.


try
{
int val = 100;
int div = 0;
int resultVal;
resultVal = (val / div);
Response.Write("The result is : " + resultVal);
}
catch (System.Exception ex)
{
Response.Write ("Exception catch here - details : " + ex.ToString());
}
finally
{
Response.Write("Enter finally block ");
}
How to throw Exception
Exception objects that describe an error are created and then thrown with the throw keyword. By
using a throw statement inside a catch block, we can change the resulting exception. More
about.... throw exception

How to create a custom exception


If you want users to be able to programmatically distinguish between some error conditions, you
should create your own custom exceptions. It will simplify and improve the error handling and
thus increase the overall code quality.
System level Exceptions Vs Application level Exceptions
System level Exceptions
System exceptions are derive directly from a base class System.SystemException. A System level
Exception is normally thrown when a nonrecoverable error has occurred, such as a database crash.
These are common exceptions that are thrown by the .NET Common Language Runtime and used
in almost all .Net applications.
Application level Exceptions
Application exceptions can be user defined exceptions thrown by the applications. If you are
designing an application that needs to create its own exceptions class, you are advised to derive
custom exceptions from the System.ApplicationException class. It is typically thrown when a
recoverable error has occurred, such as an invalid input argument values to a business method. It
will alert the client of application specific or business logic issues; they do not report system level
exceptions in most cases, clients can be return to normal processing after solving application
exceptions.
NullReferenceException
NullReferenceException indicates that you are trying to access member fields, or function types,
on an object reference that points to null. That means the reference to an Object which is not
initialized.
********For Master Page refer ASP.NET 4 Unleashed**********

Master Page

Introduction of Master Page


Microsoft ASP.NET 2.0 introduces a new feature Master Pages that permits you to define common
user interface (UI) elements and common structure in a template that can be applied to multiple
content pages in a Web application. Standard elements are, for example, navigational menus,
logos, and other stock graphical elements. This allows you to have a common appearance and
functionality across your Web site, avoids duplication of code, and makes the site easier to
maintain. If the content pages are based on the master page, all the elements defined in the master
page would automatically be defined in the content pages.

The page layout for Master Pages is easy to create, simple to maintain, and simple to assign to a
Web application. The Master page provides a single point of reference for all pages to display
standardized Web content. Master pages are completely transparent to end users and permit
developers to create Web sites where pages share a common layout. Defining a Master page is
similar to defining a normal page but saving a Master page is different from saving a normal
page. You must save the Master pages by using the .master file extension.
How to Add Master Page in Your Application
Adding a master page to your web application is straight forward. Just right click on the project
and select "Add New Item" and then select "Master Page". This will add the master page to your
project.

The master page already has the content place holder control which is used to hold and display
your contents. Let's delete that content placeholder and add it by our self. In this case we will create
two content place holders. One will be on the left and other one on the right. After you insert the
content placeholder control inside your table your master page will look something like this:

Using the master page in your aspx pages


Just add a new aspx page and name it as "first .aspx". Now you want to use the Sample1.master
file in your aspx page. Just go to the html view of your page and add a Master Page File attribute
in the page directive and delete all the other html that is written in the aspx page. The Master Page
File attribute denotes that the Page is inheriting from the master page.

<%@ Page Master Page virtual="~/Sample1.master" %>

You might also like