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

Validation Controls in ASP

The document discusses validation controls in ASP.NET that provide ways to check user input for errors. There are six types of validation controls that each check for different types of errors. The controls render as spans on the page and have properties like ControlToValidate that must be set. Validation occurs on events like button clicks and validates the controls to check for errors.

Uploaded by

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

Validation Controls in ASP

The document discusses validation controls in ASP.NET that provide ways to check user input for errors. There are six types of validation controls that each check for different types of errors. The controls render as spans on the page and have properties like ControlToValidate that must be set. Validation occurs on events like button clicks and validates the controls to check for errors.

Uploaded by

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

Validation Controls in ASP.

NET
 
An important aspect of creating ASP.NET Web pages for user input is to be able
to check that the information users enter is valid. ASP.NET provides a set of
validation controls that provide an easy-to-use but powerful way to check for
errors and, if necessary, display messages to the user.
 
There are six types of validation controls in ASP.NET
1. RequiredFieldValidation Control
2. CompareValidator Control
3. RangeValidator Control
4. RegularExpressionValidator Control
5. CustomValidator Control
6. ValidationSummary
The below table describes the controls and their work,
 
Validation Control Description
RequiredFieldValidation Makes an input control a required field
Compares the value of one input control to the
CompareValidator
value of another input control or to a fixed value
Checks that the user enters a value that falls
RangeValidator
between two values
Ensures that the value of an input control matches
RegularExpressionValidator
a specified pattern
Allows you to write a method to handle the
CustomValidator
validation of the value entered
Displays a report of all validation errors occurred
ValidationSummary
in a Web page

All validation controls are rendered in form as <span> (label are referred as
<span> on client by server)
 
Important points for validation controls
 ControlToValidate property is mandatory to all validate controls.
 One validation control will validate only one input control but
multiple validate control can be assigned to a input control.
Validation Properties
 
Usually, Validation is invoked in response to user actions like clicking submit
button or entering data. Suppose, you wish to perform validation on page when
user clicks submit button.
 
Server validation will only performed when CauseValidation is set to true.
 
When the value of the CausesValidation property is set to true, you can also use
the ValidationGroup property to specify the name of the validation group for
which the Button control causes validation.
 
Page has a Validate() method. If it is true this methods is executed. Validate()
executes each validation control.
 
To make this happen, simply set the CauseValidation property to true for submit
button as shown below:
 
<asp:Button ID="Button2" runat="server" Text="Submit"
CausesValidation=true />
 
Lets understand validation controls one by one with practical demonstration:
 

A PHP Error occurs when something is wrong in the PHP code. The error can be as
simple as a missing semicolon, or as complex as calling an incorrect variable.

To efficiently resolve a PHP issue in a script, you must understand what kind of
problem is occurring.

The four types of PHP errors are:

1. Warning Error
2. Notice Error
3. Parse Error
4. Fatal Error

Warning Error
A warning error in PHP does not stop the script from running. It only warns you that
there is a problem, one that is likely to cause bigger issues in the future.

The most common causes of warning errors are:

 Calling on an external file that does not exist in the directory


 Wrong parameters in a function

For instance:
<?php
echo "Warning error"';
include ("external_file.php");
?>

Notice Error
Notice errors are minor errors. They are similar to warning errors, as they also don’t
stop code execution. Often, the system is uncertain whether it’s an actual error or
regular code. Notice errors usually occur if the script needs access to an undefined
variable.

Example:

<?php
$a="Defined error";
echo "Notice error";
echo $b;
?>

Parse Error (Syntax)


Parse errors are caused by misused or missing symbols in a syntax. The compiler
catches the error and terminates the script.

Parse errors are caused by:

 Unclosed brackets or quotes


 Missing or extra semicolons or parentheses
 Misspellings

For example, the following script would stop execution and signal a parse error:

<?php
echo "Red";
echo "Blue";
echo "Green"
?>

It is unable to execute because of the missing semicolon in the third line.


Fatal Error
Fatal errors are ones that crash your program and are classified as critical errors. An
undefined function or class in the script is the main reason for this type of error.

There are three (3) types of fatal errors:

1. Startup fatal error (when the system can’t run the code at installation)
2. Compile time fatal error (when a programmer tries to use nonexistent data)
3. Runtime fatal error (happens while the program is running, causing the code
to stop working completely)

For instance, the following script would result in a fatal error:

<?php
function sub()
{
$sub=6-1;
echo "The sub= ".$sub;
}
div();
?>

Create a simple HTML form and accept the user name and display the name
through PHP echo statement.

HTML form: A webform or HTML form on a web page allows a user to enter
data that is sent to a server for processing. Forms can resemble paper or
database forms because web users fill out the forms using checkboxes, radio
buttons, or text fields. For example, forms can be used to enter railway or
credit card data to purchase a product, or can be used to retrieve search
results from a search engine.

Sample Solution: -

PHP Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-
8">
</head>
<body>
<form method='POST'>
<h2>Please input your name:</h2>
<input type="text" name="name">
<input type="submit" value="Submit Name">
</form>
<?php
//Retrieve name from query string and store to a local variable
$name = $_POST['name'];
echo "<h3> Hello $name </h3>";
?>
</body>
</html>

Sample Output:

Flowchart:
ASP.NET life cycle specifies, how:

 ASP.NET processes pages to produce dynamic output


 The application and its pages are instantiated and processed
 ASP.NET compiles the pages dynamically
The ASP.NET life cycle could be divided into two groups:

 Application Life Cycle


 Page Life Cycle

ASP.NET Application Life Cycle


The application life cycle has the following stages:
 User makes a request for accessing application resource, a page. Browser sends
this request to the web server.
 A unified pipeline receives the first request and the following events take
place:
o An object of the class ApplicationManager is created.
o An object of the class HostingEnvironment is created to provide
information regarding the resources.
o Top level items in the application are compiled.
 Response objects are created. The application objects such as HttpContext,
HttpRequest and HttpResponse are created and initialized.
 An instance of the HttpApplication object is created and assigned to the
request.
 The request is processed by the HttpApplication class. Different events are
raised by this class for processing the request.

ASP.NET Page Life Cycle


When a page is requested, it is loaded into the server memory, processed, and sent to the
browser. Then it is unloaded from the memory. At each of these steps, methods and events
are available, which could be overridden according to the need of the application. In other
words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components
on the page, except the directives, are part of this control tree. You can see the control tree by
adding trace= "true" to the page directive. We will cover page directives and tracing under
'directives' and 'event handling'.
The page life cycle phases are:

 Initialization
 Instantiation of the controls on the page
 Restoration and maintenance of the state
 Execution of the event handler codes
 Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen
at any stage of the page life cycle. It also helps in writing custom controls and initializing
them at right time, populate their properties with view-state data and run control behavior
code.
Following are the different stages of an ASP.NET page:
 Page request - When ASP.NET gets a page request, it decides whether to
parse and compile the page, or there would be a cached version of the page;
accordingly the response is sent.
 Starting of page life cycle - At this stage, the Request and Response objects
are set. If the request is an old request or post back, the IsPostBack property of
the page is set to true. The UICulture property of the page is also set.
 Page initialization - At this stage, the controls on the page are assigned unique
ID by setting the UniqueID property and the themes are applied. For a new
request, postback data is loaded and the control properties are restored to the
view-state values.
 Page load - At this stage, control properties are set using the view state and
control state values.
 Validation - Validate method of the validation control is called and on its
successful execution, the IsValid property of the page is set to true.
 Postback event handling - If the request is a postback (old request), the
related event handler is invoked.
 Page rendering - At this stage, view state for the page and all controls are
saved. The page calls the Render method for each control and the output of
rendering is written to the OutputStream class of the Response property of
page.
 Unload - The rendered page is sent to the client and page properties, such as
Response and Request, are unloaded and all cleanup done.

ASP.NET Page Life Cycle Events


At each stage of the page life cycle, the page raises some events, which could be coded. An
event handler is basically a function or subroutine, bound to the event, using declarative
attributes such as Onclick or handle.
Following are the page life cycle events:
 PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack
property and determines whether the page is a postback. It sets the themes and
master pages, creates dynamic controls, and gets and sets profile property
values. This event can be handled by overloading the OnPreInit method or
creating a Page_PreInit handler.
 Init - Init event initializes the control property and the control tree is built.
This event can be handled by overloading the OnInit method or creating a
Page_Init handler.
 InitComplete - InitComplete event allows tracking of view state. All the
controls turn on view-state tracking.
 LoadViewState - LoadViewState event allows loading view state information
into the controls.
 LoadPostData - During this phase, the contents of all the input fields are
defined with the <form> tag are processed.
 PreLoad - PreLoad occurs before the post back data is loaded in the controls.
This event can be handled by overloading the OnPreLoad method or creating a
Page_PreLoad handler.
 Load - The Load event is raised for the page first and then recursively for all
child controls. The controls in the control tree are created. This event can be
handled by overloading the OnLoad method or creating a Page_Load handler.
 LoadComplete - The loading process is completed, control event handlers are
run, and page validation takes place. This event can be handled by overloading
the OnLoadComplete method or creating a Page_LoadComplete handler
 PreRender - The PreRender event occurs just before the output is rendered.
By handling this event, pages and controls can perform any updates before the
output is rendered.
 PreRenderComplete - As the PreRender event is recursively fired for all child
controls, this event ensures the completion of the pre-rendering phase.
 SaveStateComplete - State of control on the page is saved. Personalization,
control state and view state information is saved. The HTML markup is
generated. This stage can be handled by overriding the Render method or
creating a Page_Render handler.
 UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises
the UnLoad event for all controls recursively and lastly for the page itself.
Final cleanup is done and all resources and references, such as database
connections, are freed. This event can be handled by modifying the OnUnLoad
method or creating a Page_UnLoad handler.

ASP.NET allows the following sources of data to be accessed and used:

 Databases (e.g., Access, SQL Server, Oracle, MySQL)


 XML documents
 Business Objects
 Flat files
ASP.NET hides the complex processes of data access and provides much higher level of
classes and objects through which data is accessed easily. These classes hide all complex
coding for connection, data retrieving, data querying, and data manipulation.
ADO.NET is the technology that provides the bridge between various ASP.NET control
objects and the backend data source. In this tutorial, we will look at data access and working
with the data in brief.

Retrieve and display data


It takes two types of data controls to retrieve and display data in ASP.NET:
 A data source control - It manages the connection to the data, selection of
data, and other jobs such as paging and caching of data etc.
 A data view control - It binds and displays the data and allows data
manipulation.
We will discuss the data binding and data source controls in detail later. In this section, we
will use a SqlDataSource control to access data and a GridView control to display and
manipulate data in this chapter.
We will also use an Access database, which contains the details about .Net books available in
the market. Name of our database is ASPDotNetStepByStep.mdb and we will use the data
table DotNetReferences.

1. <body>  
2.     <form id="form1" runat="server">  
3.     <div>  
4.       
5.         <asp:Label ID="Label1" runat="server" Text="Userna
me"></asp:Label>  
6.         <asp:TextBox ID="TextBox1" runat="server" Width="1
46px"></asp:TextBox>  
7.         <asp:RequiredFieldValidator ID="RequiredFieldValid
ator1" runat="server"   
8.             ControlToValidate="TextBox1" ErrorMessage="Ent
er username." ForeColor="Red"></
asp:RequiredFieldValidator>  
9.         <br />  
10.         Password<asp:TextBox ID="TextBox2" runat="server" 
TextMode="Password"   
11.             Width="147px"></asp:TextBox>  
12.         <asp:RequiredFieldValidator ID="RequiredFieldVali
dator2" runat="server"   
13.             ControlToValidate="TextBox2" ErrorMessage="En
ter password." ForeColor="Red"></
asp:RequiredFieldValidator>  
14.         <br />  
15.         <asp:Button ID="Button1" runat="server" onclick="
Button1_Click" Text="Log In" />  
16.         <br />  
17.         <asp:Label ID="Label2" runat="server"></
asp:Label>  
18.     </div>  
19.     </form>  
20. </body>  

https://www.geeksforgeeks.org/directives-in-jsp/

Client-side scripting Server-side scripting

Source code is not visible to the user


because its output 
Source code is visible to the of server-sideside is an HTML page. 
user.  

Its main function is to provide Its primary function is to manipulate and


the requested output to the end provide access to the respective
user. database as per the request.

In this any server-side technology can be


used and it does not 
It usually depends on the depend on the client. 
browser and its version.  

It runs on the user’s computer. It runs on the webserver.

There are many advantages The primary advantage is its ability to


Client-side scripting Server-side scripting

linked with this like faster.  highly customize, response 


response times, a more requirements, access rights based on
interactive application.  user. 
   

It does not provide security for


data. It provides more security for data.

It is a technique used in web It is a technique that uses scripts on the


development in which scripts webserver to produce a response that is
run on the client’s browser. customized for each client’s request.

HTML, CSS, and javascript are


used. PHP, Python, Java, Ruby are used.

No need of interaction with the


server. It is all about interacting with the servers.

It reduces load on processing It surge the processing load on the


unit of the server. server.

https://www.geeksforgeeks.org/how-to-calculate-multiplication-and-division-of-two-numbers-using-
javascript/

var array = [1, 2, 3, 4, 5, 6],


s = 0,
p = 1,
i;
for (i = 0; i < array.length; i += 1)
{
s += array[i];
p *= array[i];
}
console.log('Sum : '+s + ' Product : ' +p);

OR
const array = [1, 2, 3, 4, 5, 6];
let s = 0;
let p = 1;
let i;
for (i = 0; i < array.length; i += 1)
{
s += array[i];
p *= array[i];
}
console.log(`Sum : ${s} Product : ${p}`);

https://www.javatpoint.com/how-to-check-a-radio-button-using-javascript

https://www.tutorialspoint.com/javascript/javascript_events.htm#:~:text=JavaScript's
%20interaction%20with%20HTML%20is,%2C%20resizing%20a%20window%2C%20etc.

https://www.geeksforgeeks.org/how-to-run-a-function-when-the-page-is-loaded-in-javascript/

You might also like