0% found this document useful (0 votes)
9 views9 pages

Lab 5

This document covers the basics of error handling, form validation, and cookie management in JavaScript. It explains the use of try-catch-finally blocks for error handling, provides examples of form validation for user inputs, and demonstrates how to create and manage cookies. Additionally, it includes practical exercises and code snippets for implementing these concepts in web applications.

Uploaded by

cameronrobin495
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)
9 views9 pages

Lab 5

This document covers the basics of error handling, form validation, and cookie management in JavaScript. It explains the use of try-catch-finally blocks for error handling, provides examples of form validation for user inputs, and demonstrates how to create and manage cookies. Additionally, it includes practical exercises and code snippets for implementing these concepts in web applications.

Uploaded by

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

LAB 5: BASIC OF ERROR HANDLING, FORM VALIDATION AND

COOKIES
THEORY
JavaScript is a loosely-typed language. It does not give compile-time errors. So
some times you will get a runtime error for accessing an undefined variable or
calling undefined function etc.
JavaScript provides error-handling mechanism to catch runtime errors
using try-catch-finally block.
try
{
// code that may throw an error
}
catch(ex)
{
// code to be executed if an error occurs
}
finally{
// code to be executed regardless of an error occurs or not
}
The try statement allows you to define a block of code to be tested for errors
while it is being executed.

The catch statement allows you to define a block of code to be executed, if an


error occurs in the try block.

The throw statement allows you to create a custom error.


DOM (Document Object Model)
The Document Object Model (DOM) is the data representation of the objects
that comprise the structure and content of a document on the web. This guide
will introduce the DOM, look at how the DOM represents an HTML document
in memory and how to use APIs to create web content and applications.
getElementByID: The most common way to access an HTML element is to use
the id of the element
innerHTML: The easiest way to get the content of an element is by using the
innerHTML property.

Form Validation
JavaScript provides a way to validate form's data on the client's computer before
sending it to the web server. Form validation generally performs two functions.
Basic Validation − The form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form
and check for data.

Data Format Validation − The data that is entered must be checked for correct
form and value. Your code must include appropriate logic to test correctness of
data.

JavaScript Cookies
A cookie is an amount of information that persists between a server-side and a
client-side. A web browser stores this information at the time of browsing.

A cookie contains the information as a string generally in the form of a name-


value pair separated by semi-colons. It maintains the state of a user and
remembers the user's information among all the web pages.

QUESTIONS
1.Illustrate the concept of runtime error handling in JavaScript. Make proper use
of try…catch statement, throw statement and finally statement.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible"
content="IE=edge" />
<meta name="viewport" content="width=device-
width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="q1.js"></script>
<button onclick="try_block()">try block</button>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible"
content="IE=edge" />
<meta name="viewport" content="width=device-
width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="q1.js"></script>
<button onclick="try_block()">try block</button>
</body>
</html>
OUTPUT

2.Design a form consisting of following elements and apply proper validations


as mentioned below.
a. A textbox to accept User Name which should not be empty
b. A textbox to accept User Code. The code should start with @ followed by a
sequence of four digits further followed by a sequence of four alphabets which
can be capital or small and end with #.
c. A textbox to accept mobile number i.e. must start with 98… and should have
10 digits
d. A radio button to accept gender which should be checked.
e. A dropdown that selects the Province Number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible"
content="IE=edge" />
<meta name="viewport" content="width=device-
width, initial-scale=1.0" />
<title>Form</title>
<script src="q2.js"></script>
</head>
<body>
<form onsubmit="return validate()">
<label for="username">Username</label>
<input type="text" name="username"
id="username" />
<br />
<label for="usercode">User Code</label>
<input type="text" name="usercode"
id="usercode" />
<br />
<label for="mobile">Moblie Number</label>
<input type="text" name="mobile" id="mobile" />
<br />
<label for="Gender">Gender</label>
<input type="radio" name="gender"
id="gender" />Male
<input type="radio" name="gender"
id="gender" />Female
<br />
<label for="Province"
>Province:
<select name="Province" id="Province">
<option value="1">Province1</option>
<option value="2">Province2</option>
<option value="3">Province3</option>
<option value="4">Province4</option>
<option value="5">Province5</option>
<option value="6">Province6</option>
<option value="7">Province7</option>
</select>
</label>
<br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

function validate(){
let
username=document.getElementById("username").value;
let
usercode=document.getElementById("usercode").value;
let
Mobilenumber=document.getElementById("mobile").value;
let gender=document.getElementsByName("gender");
let pat1=/^@[0-9]{4}[a-z A-Z]{4}#$/;
let pat2=/^98[0-9]{8}$/;
if(username=="")
{
alert("Enter username.");
return false;
}
else if(!(gender[0].checked ||
gender[1].checked))
{
alert("Select a gender.")
return false;
}
else if (!(pat1.test(usercode))){
alert("Invalid code.");
return false;
}
else if (!(pat2.test(Mobilenumber))){
alert("Invalid number.");
return false;
}
else
{
alert("Form submitted successfully.")
}
}
// else if(Province=="")
// {
// alert("Select a province.");
// return false;
// }
3.Illustrate the concept of cookie in JavaScript. Whenever a page loads first
check whether cookie is expired or not. If cookie is not active/expire then first
ask the user name and set it as cookie. If the cookie has not expired then give
appropriate greeting.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible"
content="IE=edge" />
<meta name="viewport" content="width=device-
width, initial-scale=1.0" />
<title>Cookie In Javascript</title>
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + exdays * 24 * 60 * 60
* 1000);
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";"
+ expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie =
decodeURIComponent(document.cookie);
var ca = decodedCookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,
c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:",
"");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body>
<h1>Cookie In Javascript</h1>
<button onclick="checkCookie()">Check
Cookie</button>
</body>
</html>
OUTPUT

4.Create a date object and make the use of following methods:


a. getDate()
b.getMonth()
c. getDay()
d. getHours()
e. getMinutes()
f. getMilliseconds()
<!-- Create a date object and make the use of
following methods -->
<!-- getFullYear(), getMonth(), getDate(), getDay(),
getHours(), getMinutes(), getSeconds(),
getMilliseconds() -->
<!-- getYear() -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible"
content="IE=edge" />
<meta name="viewport" content="width=device-
width, initial-scale=1.0" />
<title>Date Functions</title>
<script>
function dateFunctions() {
var d = new Date();
document.getElementById("date").innerHTML =
d;
document.getElementById("year").innerHTML =
d.getFullYear();
document.getElementById("month").innerHTML =
d.getMonth();
document.getElementById("date1").innerHTML =
d.getDate();
document.getElementById("day").innerHTML =
d.getDay();
document.getElementById("hours").innerHTML =
d.getHours();
document.getElementById("minutes").innerHTML
= d.getMinutes();
document.getElementById("seconds").innerHTML
= d.getSeconds();

document.getElementById("milliseconds").innerHTML =
d.getMilliseconds();
}
</script>
</head>
<body>
<h1>Date Functions</h1>
<button onclick="dateFunctions()">Date
Functions</button>
<p id="date"></p>
<p id="year"></p>
<p id="month"></p>
<p id="date1"></p>
<p id="day"></p>
<p id="hours"></p>
<p id="minutes"></p>
<p id="seconds"></p>
<p id="milliseconds"></p>
</body>
</html>
OUTPUT

CONCLUSION
In conclusion, we explored the fundamentals of form validation, error
management, and cookie handling and put them into practice to build a website.

You might also like