1. Index
Assignment
NO:
Name of Practical Assignment Signature
1 Create an HTML form that contain the Student Registration
details and write a JavaScript to validate Student first and last
name as it should not contain other than alphabets and age
should be between 18 to 50.
2 Create an HTML form that contain the Employee Registration
details and write a JavaScript to validate DOB, Joining Date,
and Salary.
3 Create an HTML form for Login and write a JavaScript to
validate email ID using Regular Expression.
4 Write angular JS by using ng-click Directive to display an alert
message after clicking the element
5 Write an AngularJS script for addition of two numbers using
ng-init, ng-model & ng bind. And also Demonstrate ng-show,
ng-disabled, ng-click directives on button component.
6 Using angular js display the 10 student details in Table format
(using ng-repeat directive use Array to store data
7 Using angular js Create a SPA that show Syllabus content of all
subjects of MSC(CS) Sem II (use ng-view)
8 Using angular js create a SPA to accept the details such as
name, mobile number, pincode and email address and make
validation. Name should contain character only, SPPU M.Sc.
Computer Science Syllabus 2023-24 59 mobile number should
contain only 10 digit, Pincode should contain only 6 digit,
email id should contain only one @, . Symbol
9 Create an HTML form using AngularJS that contain the Student
Registration details and validate Student first and last name as it
should not contain other than alphabets and age should be
between 18 to 50 and display greeting message depending on
current time using ng-show (e.g. Good Morning, Good
Afternoon, etc.)(Use AJAX).
10 Create angular JS Application that show the current Date and
Time of the System(Use Interval Service)
11 Using angular js create a SPA to carry out validation for a
username entered in a textbox. If the textbox is blank, alert
„Enter username‟. If the number of characters is less than three,
alert ‟ Username is too short‟. If value entered is appropriate
the print „Valid username‟ and password should be minimum 8
characters
12 Create a Node.js file that will convert the output "Hello
World!" into upper-case letters
13 Using nodejs create a web page to read two file names from
user and append contents of first file into second file
14 Create a Node.js file that opens the requested file and returns
the content to the client If anything goes wrong, throw a 404
erro
2. 15 Create a Node.js file that writes an HTML form, with an upload
field
16 Create a Node.js file that demonstrate create database and table
in MySQL
17 Create a node.js file that Select all records from the "customers"
table, and display the result object on console
18 Create a node.js file that Insert Multiple Records in "student"
table, and display the result object on console
19 Create a node.js file that Select all records from the "customers"
table, and delete the specified record.
20 Create a Simple Web Server using node js
21 Using node js create a User Login System
22 Write node js script to interact with the file system, and serve a
web page from a File
3. Assignment no: 1
Create an HTML form that contain the Student Registration details and write a
JavaScript to validate Student first and last name as it should not contain other than
alphabets and age should be between 18 to 50.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function validateName() {
var firstName = document.querySelector("#first-name").value;
var lastName = document.querySelector("#last-name").value;
var namePattern = /^[A-Za-z]+$/;
if (!namePattern.test(firstName) || !namePattern.test(lastName)) {
alert("Please enter valid first and last names (only alphabets).");
return false;
}
return true;
}
function validateAge() {
var age = parseInt(document.querySelector("#age").value);
if (isNaN(age) || age < 18 || age > 50) {
alert("Age must be between 18 and 50.");
return false;
}
return true;
}
function validateForm() {
var isValidName = validateName();
var isValidAge = validateAge();
if (isValidName && isValidAge) {
alert("Registration successful!");
return true;
} else {
alert("One or more fields are incorrectly set.");
return false;
}
4. }
</script>
</head>
<body>
<h2>STUDENT REGISTRATION FORM</h2>
<form name="registrationForm" method="post" onsubmit="return
validateForm()">
<label for="first-name">First Name:</label>
<input type="text" id="first-name" required><br>
<label for="last-name">Last Name:</label>
<input type="text" id="last-name" required><br>
<label for="age">Age:</label>
<input type="number" id="age" min="18" max="50" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>
Output:
Assignment no: 2
Create an HTML form that contain the Employee Registration details and write a
JavaScript to validate DOB, Joining Date, and Salary.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Employee Registration Form</title>
<script type="text/javascript">
5. function validateDOB() {
var dob = document.querySelector("#dob").value;
var dobDate = new Date(dob);
var currentDate = new Date();
if (dobDate >= currentDate) {
alert("Please enter a valid Date of Birth.");
return false;
}
return true;
}
function validateJoiningDate() {
var joiningDate = document.querySelector("#joining-date").value;
var joiningDateDate = new Date(joiningDate);
if (joiningDateDate >= new Date()) {
alert("Joining Date cannot be in the future.");
return false;
}
return true;
}
function validateSalary() {
var salary = parseFloat(document.querySelector("#salary").value);
if (isNaN(salary) || salary <= 0) {
alert("Please enter a valid positive Salary amount.");
return false;
}
return true;
}
function validateForm() {
var isValidDOB = validateDOB();
var isValidJoiningDate = validateJoiningDate();
var isValidSalary = validateSalary();
if (isValidDOB && isValidJoiningDate && isValidSalary) {
alert("Employee registration successful!");
return true;
} else {
alert("One or more fields are incorrectly set.");
return false;
}
}
14. Assignment no: 8
Using angular js create a SPA to accept the details such as name, mobile number,
pincode and email address and make validation. Name should contain character
only, SPPU M.Sc. Computer Science Syllabus 2023-24 59 mobile number should
contain only 10 digit, Pincode should contain only 6 digit, email id should contain
only one @, . Symbol
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<h2>User Details</h2>
<form name="userForm">
<p>
<label for="name">Name:</label>
<input type="text" id="name" ng-model="user.name" required pattern="[A-
Za-z ]+">
</p>
<p>
<label for="mobile">Mobile Number:</label>
<input type="tel" id="mobile" ng-model="user.mobile" required pattern="[0-
9]{10}">
</p>
<p>
<label for="pincode">Pincode:</label>
<input type="text" id="pincode" ng-model="user.pincode" required
pattern="[0-9]{6}">
</p>
<p>
<label for="email">Email Address:</label>
<input type="email" id="email" ng-model="user.email" required>
</p>
<button ng-click="validateUser()" ng-
disabled="userForm.$invalid">Submit</button>
</form>
<div ng-show="submitted">
<h3>Submitted Details:</h3>
<p>Name: {{ user.name }}</p>
<p>Mobile Number: {{ user.mobile }}</p>
<p>Pincode: {{ user.pincode }}</p>
<p>Email Address: {{ user.email }}</p>
15. </div>
<script>
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
$scope.user = {}; // Initialize user object
$scope.submitted = false;
$scope.validateUser = function () {
// Perform additional validation if needed
// For now, just mark as submitted
$scope.submitted = true;
};
});
</script>
</body>
</html>
16. Output:
Assignment no: 9
Create an HTML form using AngularJS that contain the Student Registration details
and validate Student first and last name as it should not contain other than
alphabets and age should be between 18 to 50 and display greeting message
depending on current time using ng-show (e.g. Good Morning, Good Afternoon,
etc.)(Use AJAX).
17. <!DOCTYPE html>
<html ng-app="studentApp">
<head>
<title>Student Registration Form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
}
</style>
</head>
<body ng-controller="StudentController">
<h1>Student Registration Form</h1>
<form name="registrationForm" novalidate>
<p>
First Name:
<input
type="text"
name="firstName"
ng-model="student.firstName"
ng-pattern="/^[a-zA-Z]*$/"
required
/>
<span ng-show="registrationForm.firstName.$error.pattern">
First name should contain only alphabets.
</span>
</p>
<p>
Last Name:
<input
type="text"
name="lastName"
ng-model="student.lastName"
ng-pattern="/^[a-zA-Z]*$/"
required
/>
<span ng-show="registrationForm.lastName.$error.pattern">
Last name should contain only alphabets.
</span>
</p>
<p>
Age:
<input
type="number"
name="age"
18. ng-model="student.age"
min="18"
max="50"
required
/>
<span ng-show="registrationForm.age.$error.min ||
registrationForm.age.$error.max">
Age must be between 18 and 50.
</span>
</p>
<p>
<button type="submit">Register</button>
</p>
</form>
<div ng-show="greetingMessage">
<p>{{ greetingMessage }}</p>
</div>
<script>
angular.module('studentApp', []).controller('StudentController', function ($scope)
{
$scope.student = {
firstName: '',
lastName: '',
age: null,
};
// Determine the greeting message based on the current time
var currentTime = new Date().getHours();
if (currentTime >= 5 && currentTime < 12) {
$scope.greetingMessage = 'Good Morning!';
} else if (currentTime >= 12 && currentTime < 18) {
$scope.greetingMessage = 'Good Afternoon!';
} else {
$scope.greetingMessage = 'Good Evening!';
}
});
</script>
</body>
</html>
Output:
19. Assignment no: 10
Create angular JS Application that show the current Date and Time of the
System(Use Interval Service)
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Current Date and Time</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<h1>Current Date and Time</h1>
<p>The current time is: {{ theTime }}</p>
<script>
angular.module('myApp', []).controller('MyController', function ($scope,
$interval) {
20. $interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
</script>
</body>
</html>
Output:
Assignment no: 11
Using angular js create a SPA to carry out validation for a username entered in a
textbox. If the textbox is blank, alert „Enter username‟. If the number of characters
is less than three, alert ‟ Username is too short‟. If value entered is appropriate the
print „Valid username‟ and password should be minimum 8 characters
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Username Validation</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
</head>
<body ng-controller="ValidationController">
<h1>Username Validation</h1>
<input type="text" ng-model="username" placeholder="Enter username">
<button ng-click="validateUsername()">Validate</button>
<div ng-show="validationMessage">
21. {{ validationMessage }}
</div>
<script>
angular.module('myApp', [])
.controller('ValidationController', function ($scope) {
$scope.validateUsername = function () {
if (!$scope.username) {
$scope.validationMessage = 'Enter username';
} else if ($scope.username.length < 3) {
$scope.validationMessage = 'Username is too short';
} else {
$scope.validationMessage = 'Valid username';
}
};
});
</script>
</body>
</html>
Output:
22. Assignment no: 12
Create a Node.js file that will convert the output "Hello World!" into upper-case
letters
var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
Output:
Assignment no: 13
Using nodejs create a web page to read two file names from user and append
contents of first file into second file
// Import necessary modules
const fs = require('fs');
23. const express = require('express');
const bodyParser = require('body-parser');
// Create an Express app
const app = express();
// Middleware to parse form data
app.use(bodyParser.urlencoded({ extended: true }));
// Serve an HTML form to the user
app.get('/', (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(`
<html>
<body>
<h1>Select 2 files to append File1 contents to File2</h1>
<form method="post" action="/append">
<input type="text" name="file1" placeholder="Enter File1 name"
required><br>
<input type="text" name="file2" placeholder="Enter File2 name"
required><br>
<input type="submit" value="Append">
</form>
</body>
</html>
`);
res.end();
});
// Handle form submission
app.post('/append', (req, res) => {
const file1 = req.body.file1;
const file2 = req.body.file2;
// Read contents of File1
fs.readFile(file1, 'utf8', (err, data) => {
if (err) {
res.status(500).send(`Error reading ${file1}: ${err.message}`);
} else {
// Append contents of File1 to File2
fs.appendFile(file2, data, (appendErr) => {
if (appendErr) {
res.status(500).send(`Error appending to ${file2}: ${appendErr.message}`);
} else {
res.send(`Contents of ${file1} appended to ${file2}`);
}
24. });
}
});
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Output:
Assignment no: 14
Create a Node.js file that opens the requested file and returns the content to the
client If anything goes wrong, throw a 404 error
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// Extract the requested file name from the URL
const fileName = req.url.slice(1); // Remove the leading slash
// Construct the file path
const filePath = path.join(__dirname, fileName);
// Check if the file exists
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
// File not found (404 error)
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File not found');
25. } else {
// Read the file and return its content
fs.readFile(filePath, 'utf8', (readErr, data) => {
if (readErr) {
// Error reading the file
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal server error');
} else {
// Successful response
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(data);
}
});
}
});
});
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Output:
26. Assignment no: 15
Create a Node.js file that writes an HTML form, with an upload field
// Import the required modules
const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
// Create an HTTP server
http.createServer(function (req, res) {
if (req.url === '/fileupload') {
// Handle file upload
const form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
if (err) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Error parsing form data.');
return;
}
// Move the uploaded file to a desired location
const oldPath = files.filetoupload.path;
const newPath = 'C:UsershrushDesktopcoding practiceweb' +
files.filetoupload.name; // Specify your desired path
fs.rename(oldPath, newPath, function (err) {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error moving file.');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('File uploaded and moved successfully!');
});
});
} else {
// Display the upload form
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<form action="fileupload" method="post" enctype="multipart/form-
data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
res.end();
}
28. Assignment no: 16
Create a Node.js file that demonstrate create database and table in MySQL
const mysql = require('mysql2');
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234'
});
con.connect(function (err) {
if (err) throw err;
console.log('Connected to MySQL server!');
con.query('CREATE DATABASE mydb', function (err, result) {
if (err) throw err;
console.log('Database "mydb" created successfully!');
});
//const mysql = require('mysql');
const con2 = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb' // Specify the database you created earlier
});
con2.connect(function (err) {
if (err) throw err;
console.log('Connected to MySQL server!');
const createTableQuery = `
CREATE TABLE authors (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
)
`;
con2.query(createTableQuery, function (err, result) {
if (err) throw err;
console.log('Table "authors" created successfully!');
});
29. });
});
Output:
Assignment no: 17
Create a node.js file that Select all records from the "customers" table, and display
the result object on console
const mysql = require('mysql2');
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb' // Replace with your actual database name
});
con.connect(function(err) {
if (err) throw err;
console.log('Connected to MySQL server!');
con.query('SELECT * FROM authors', function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Output:
30. Assignment no: 18
Create a node.js file that Insert Multiple Records in "student" table, and display the
result object on console.
const mysql = require('mysql2');
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb' // Replace with your actual database name
});
con.connect(function(err) {
if (err) throw err;
console.log('Connected to MySQL server!');
// Data for multiple student records
const students = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 22 },
{ name: 'Charlie', age: 21 }
// Add more student objects as needed
];
// Prepare the SQL query for bulk insertion
const insertQuery = 'INSERT INTO student (name, age) VALUES ?';
const values = students.map(student => [student.name, student.age]);
// Execute the query
con.query(insertQuery, [values], function(err, result) {
if (err) throw err;
console.log('Inserted ' + result.affectedRows + ' rows into the "student" table.');
console.log('Last insert ID:', result.insertId);
});
con.query('SELECT * FROM student', function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Output:
31. Assignment no: 19
Create a node.js file that Select all records from the "customers" table, and delete
the specified record.
// select_and_delete.js
const mysql = require('mysql2');
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb', // Replace with your database name
});
con.connect((err) => {
if (err) throw err;
// Select all records from the "customers" table
con.query('SELECT * FROM customers', (err, result) => {
if (err) throw err;
console.log('All records from "customers" table:');
console.log(result);
});
// Add this after the SELECT query
const addressToDelete = 'pune';
const deleteQuery = `DELETE FROM customers WHERE address =
'${addressToDelete}'`;
con.query(deleteQuery, (err, result) => {
if (err) throw err;
console.log(`Number of records deleted: ${result.affectedRows}`);
});
32. });
Output:
Assignment no: 20
Create a Simple Web Server using node js.
// index.js
const http = require('http');
const server = http.createServer((req, res) => {
res.write('This is the response from the server');
res.end();
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
Output:
33. Assignment no: 21
Using node js create a User Login System.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple User Login</title>
</head>
<body>
<h1>User Login</h1>
<form action="/login" method="post">
<label for="username">Enter Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Enter Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
</body>
</html>
// app.js
const express = require('express');
const mysql = require('mysql2');
const app = express();
const PORT = 3000;
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb', // Replace with your database name
});
db.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database');
});
// Middleware to parse form data
app.use(express.urlencoded({ extended: true }));
34. // Serve the HTML form
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Handle form submission
app.post('/login', (req, res) => {
const username = req.body.username;
const password = parseInt(req.body.password);
const query = `SELECT * FROM users WHERE username = '${username}' AND
password = '${password}'`;
db.query(query, [username, password], (err, results) => {
if (err) throw err;
if (results.length > 0) {
res.send(`Hello! ${username} Welcome to Dashboard`);
console.log(results);
} else {
res.send('Invalid credentials. Please try again.');
}
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running, and app is listening on port ${PORT}`);
});