0% found this document useful (0 votes)
14 views25 pages

Exp-7 & EXP-9

The document contains multiple programming statements and source code examples demonstrating various JavaScript concepts, including form validation, document and window object methods, array operations, math functions, string manipulations, regex operations, date object methods, and user-defined objects. Each section provides a brief description of the concepts followed by HTML and JavaScript code snippets that illustrate their usage. The examples cover a wide range of functionalities, showcasing how to interact with the DOM and utilize built-in JavaScript objects.
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)
14 views25 pages

Exp-7 & EXP-9

The document contains multiple programming statements and source code examples demonstrating various JavaScript concepts, including form validation, document and window object methods, array operations, math functions, string manipulations, regex operations, date object methods, and user-defined objects. Each section provides a brief description of the concepts followed by HTML and JavaScript code snippets that illustrate their usage. The examples cover a wide range of functionalities, showcasing how to interact with the DOM and utilize built-in JavaScript objects.
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/ 25

Program Statement:

9C) Write a program to validate the following fields in a registration page:


i. Name (start with alphabet and followed by alphanumeric and the
length should not be less than 6 characters).
ii. Mobile (only numbers and length 10 digits).
iii. E-mail (should contain format like [email protected])

Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
<style>
.container {
max-width: 400px;
margin: 50px auto;
padding: 20px;
border: 2px solid green;
border-radius: 10px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
}

input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}

.error {
color: red;
font-size: 12px;
display: none;
}
button {
background-color:Green;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>Registration Form</h2>
<form id="registrationForm" onsubmit="return validateForm(event)">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<span class="error" id="nameError">Name must start with a letter
and be at least 6 characters long</span>
</div>
<div class="form-group">
<label for="mobile">Mobile:</label>
<input type="tel" id="mobile" name="mobile" required>
<span class="error" id="mobileError">Mobile must be 10
digits</span>
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<span class="error" id="emailError">Please enter a valid email
address</span>
</div>

<button type="submit">Register</button>
</form>
</div>

<script>
function validateForm(event) {
event.preventDefault();
let isValid = true;

// Name validation
const name = document.getElementById('name').value;
const nameRegex = /^[A-Za-z][A-Za-z0-9]{5,}$/;
const nameError = document.getElementById('nameError');
if (!nameRegex.test(name)) {
nameError.style.display = 'block';
isValid = false;
} else {
nameError.style.display = 'none';
}

// Mobile validation
const mobile = document.getElementById('mobile').value;
const mobileRegex = /^\d{10}$/;
const mobileError = document.getElementById('mobileError');
if (!mobileRegex.test(mobile)) {
mobileError.style.display = 'block';
isValid = false;
} else {
mobileError.style.display = 'none';
}

// Email validation
const email = document.getElementById('email').value;
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const emailError = document.getElementById('emailError');
if (!emailRegex.test(email)) {
emailError.style.display = 'block';
isValid = false;
} else {
emailError.style.display = 'none';
}

if (isValid) {
alert('Form submitted successfully!');
document.getElementById('registrationForm').reset();
}

return isValid;
}
</script>
</body>
</html>
Output:
WEEK-7
Program Statement:
a). Write a program using document object properties and methods.

Description:
- document.getElementById(): Returns an element with the specified ID.
- element.innerText: Sets or returns the text content of an element.
- element.style.display: Sets or returns the display style of an element.

Source Code:
<html>
<head>
<title>web page</title>
</head>
<body>
<h1 id="Welcome"> JAVASCRIPT</h1>
<button onclick="changeText()">Change Text</button>
<button onclick="hideElement()">Hide Element</button>
<button onclick="showElement()">Show Element</button>
<script>
function changeText() {
var heading = document.getElementById("Welcome");
heading.innerText = "New Text!";
}
function hideElement() {
var heading = document.getElementById("Welcome");
heading.style.display = "none";
}
function showElement() {
var heading = document.getElementById("Welcome");
heading.style.display = "block";
}
</script> </body> </html>
Output:
Program Statement:
b.Write a program using window object properties and methods.

Description:
- window.open(): Opens a new browser window.
- window.close(): Closes a browser window.
- window.alert(): Displays an alert message.
- window.confirm(): Displays a confirmation message.
- window.prompt(): Displays a prompt message.

Source Code:
<html>
<head>
<title>web page</title>
</head>
<body>
<button onclick="openWindow()">Open Window</button>
<button onclick="closeWindow()">Close Window</button>
<button onclick="alertMessage()">Alert Message</button>
<button onclick="confirmMessage()">Confirm Message</button>
<button onclick="promptMessage()">Prompt Message</button>
<script>
var newWindow;
function openWindow() {
newWindow = window.open("https://www.google.com", "_blank",
"width=400,height=300");
}
function closeWindow() {
newWindow.close();
}
function alertMessage() {
window.alert("This is an alert message!");
}
function confirmMessage() {
var response = window.confirm("Are you sure you want to continue?");
if (response) {
window.alert("You clicked OK!");
} else {
window.alert("You clicked Cancel!");
}
}
function promptMessage() {
var response = window.prompt("What is your name?", "");
window.alert("Your name is: " + response);
}
</script>
</body>
</html>
Output:
Program Statement:
c).Write a program using array object properties and methods.
Description:
- length: Returns the number of elements in the array.
- push(): Adds one or more elements to the end of the array.
- pop(): Removes the last element from the array.
- shift(): Removes the first element from the array.
- unshift(): Adds one or more elements to the beginning of the array.
- indexOf(): Returns the index of the first occurrence of a specified element.
- includes(): Returns a boolean indicating whether an element exists in the array.
- join(): Converts the array to a string, using a specified separator.
- slice(): Returns a subset of elements from the array.
- splice(): Inserts or removes elements from the array.
Source Code:
<html>
<head>
<title>web page</title>
</head>
<body>
<h1>Array Object Properties and Methods</h1>
<button onclick="arrayOperations()">Perform Array Operations</button>
<div id="result"></div>
<script>
function arrayOperations() {
var colors = ["Red", "Green", "Blue"];
var result = "Number of elements: " + colors.length + "<br>";
colors.push("Yellow");
result += "Array after push(): " + colors + "<br>";
var index = colors.indexOf("Green");
result += "Index of Green: " + index;
document.getElementById("result").innerHTML = result;
}
</script>
</body>
</html>
Output:
Program Statement:

d.Write a program using math object properties and methods.

Description:
- Math.PI: Returns the value of pi.
- Math.pow(): Returns the value of a number raised to a power.
- Math.sqrt(): Returns the square root of a number.
Source Code:
<html>
<head>
<title>web page</title>
</head>
<body>
<h1>Math Object Properties and Methods</h1>
<button onclick="mathOperations()">Perform Math Operations</button>
<div id="result"></div><script>
function mathOperations() {
var result = "Value of pi: " + Math.PI + "<br>";
var square = Math.pow(5, 2);
result += "Square of 5: " + square + "<br>";
var sqrt = Math.sqrt(25);
result += "Square root of 25: " + sqrt + "<br>";
var random = Math.random();
result += "Random number: " + random;
document.getElementById("result").innerHTML = result;}
</script>
</body>
</html>
Output:
Program Statement:
e. Write a program using string object properties and methods.

Description:
- length: Returns the length of the string.
- toUpperCase(): Returns the string in uppercase.
- toLowerCase(): Returns the string in lowercase.
- indexOf(): Returns the index of the first occurrence of a substring.
- replace(): Replaces a substring with another string.
Source Code:
<html>
<head><title>web page</title>
</head><body>
<h1>String Object Properties and Methods</h1>
<button onclick="stringOperations()">Perform String Operations</button>
<div id="result"></div><script>
function stringOperations() {
var str = "Hello, yashaswini";
var result = "Length of the string: " + str.length + "<br>";
var uppercase = str.toUpperCase();
result += "String in uppercase: " + uppercase + "<br>";
var index = str.indexOf("yashaswini");
result += "Index of 'yashaswini': " + index;
document.getElementById("result").innerHTML = result;}
</script></body>
</html>
Output:
Program Statement:
f). Write a program using regex object properties and methods.

Description:
- test(): Tests if a string matches the regex pattern.
- exec(): Executes a search for a match and returns an array containing the
match and subgroups.
- toString(): Converts the regex pattern to a string.
Source Code:
<html>
<head>
<title>web page</title>
</head>
<body>
<h1>Regex Object Properties and Methods</h1>
<button onclick="regexOperations()">Perform Regex Operations</button>
<div id="result"></div>
<script>
function regexOperations() {
var pattern = /hello/i;
var str = "Hello, World!";
var result = "Does '" + str + "' match the pattern? " + pattern.test(str) + "<br>";
var match = pattern.exec(str);
result += "Match: " + match[0] + "<br>";
result += "Regex pattern as a string: " + pattern.toString();
document.getElementById("result").innerHTML = result;
}
</script>
</body>
</html>
Output:
Program statement:
g). Write a program using date object properties and methods.

Description:
- getDate(): Returns the day of the month.
- getMonth(): Returns the month.
- getFullYear(): Returns the year.
- getHours(): Returns the hour.
- getMinutes(): Returns the minute.
- getTime(): Returns the number of milliseconds since January 1, 1970.
Source Code:
<html>
<head><title>web page</title></head>
<body>
<h1>Date Object Properties and Methods</h1>
<button onclick="dateOperations()">Perform Date Operations</button>
<div id="result"></div><script>
function dateOperations() {
var date = new Date();
var result = "Day of the month: " + date.getDate() + "<br>";
result += "Month: " + (date.getMonth() + 1) + "<br>";
result += "Year: " + date.getFullYear() + "<br>";
result += "Hour: " + date.getHours() + "<br>";
result += "Minute: " + date.getMinutes() + "<br>";
result += "Number of milliseconds since January 1, 1970: " + date.getTime();
document.getElementById("result").innerHTML = result;}
</script>
</body>
</html>
Output:
Program Statement:
h). Write a program to explain user-defined object by using properties,
methods, accessors, constructors and display.

Description:

- Constructor: The Person function is a constructor that initializes new objects with the
given name and age.
- Properties: The occupation property is defined using the prototype property, and the age
property is defined using the Object.defineProperty method.
- Methods: The greet and displayInfo methods are defined using the prototype property.
- Accessors: The age property has getter and setter accessors defined using the
Object.defineProperty method.
- Display: The program displays the person's information using the displayInfo method and
logs messages to the console using console.log.

Source Code:
<html>
<head>
<title>web page</title>
</head>
<body>
<h1>User-Defined Object</h1>
<button onclick="createPerson()">Create Person</button>
<div id="result"></div>
<script>
function Person(name, age) {
this.name = name;
this.age = age; }
Person.prototype.occupation = "Software Developer";
Person.prototype.greet = function() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
};
Person.prototype.displayInfo = function() {
return `Name: ${this.name}\nAge: ${this.age}\nOccupation: ${this.occupation}`;
};
Object.defineProperty(Person.prototype, "age", {
get: function() {
return this._age;
},
set: function(value) {
if (value >= 0) {
this._age = value;
} else {
throw new Error("Age cannot be negative.");
}}
});
function createPerson() {
try {
var person = new Person("yashu",19 );
var result = person.displayInfo() + "\n\n" + person.greet();
document.getElementById("result").innerHTML = result;
} catch (error) {
document.getElementById("result").innerHTML = error.message;
}}
</script>
</body>
</html>
Output:

You might also like