SlideShare a Scribd company logo
1 of 36
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
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
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;
}
}
</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">
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;
}
}
</script>
</head>
<body>
<h2>EMPLOYEE REGISTRATION FORM</h2>
<form name="employeeForm" onsubmit="return validateForm()">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" required><br>
<label for="joining-date">Joining Date:</label>
<input type="date" id="joining-date" required><br>
<label for="salary">Salary:</label>
<input type="number" id="salary" min="1" step="any" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>
Output:
Assignment no: 3
Create an HTML form for Login and write a JavaScript to validate email ID using
Regular Expression.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Form</title>
<script type="text/javascript">
function validateEmail() {
var email = document.querySelector("#email").value;
var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
if (!emailPattern.test(email)) {
alert("Please enter a valid email address.");
return false;
}
return true;
}
function validateForm() {
var isValidEmail = validateEmail();
if (isValidEmail) {
alert("Login successful!");
return true;
} else {
alert("Invalid email address.");
return false;
}
}
</script>
</head>
<body>
<h2>LOGIN FORM</h2>
<form name="loginForm" onsubmit="return validateForm()">
<label for="email">Email:</label>
<input type="email" id="email" required><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Output:
Assignment no: 4
Write angular JS by using ng-click Directive to display an alert message after clicking
the element
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">
<h2>LOGIN FORM</h2>
<div ng-controller="LoginController">
<label for="email">Email:</label>
<input type="email" id="email" ng-model="userEmail" required><br>
<button ng-click="showAlert()">Login</button>
</div>
<script>
angular.module('myApp', [])
.controller('LoginController', function ($scope) {
$scope.showAlert = function () {
alert('Login successful!'); // Display an alert message
};
});
</script>
</body>
</html>
Output:
Assignment no: 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.
<!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>Calculator</h2>
<p>First Number: <input type="number" ng-model="a" /></p>
<p>Second Number: <input type="number" ng-model="b" /></p>
<p>Sum: <span ng-bind="a + b"></span></p>
<button ng-click="calculateSum()" ng-show="a && b" ng-disabled="!a ||
!b">Calculate</button>
<script>
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
$scope.calculateSum = function () {
$scope.sum = $scope.a + $scope.b;
};
});
</script>
</body>
</html>
Output:
Assignment no: 6
Using angular js display the 10 student details in Table format (using ng-repeat
directive use Array to store data )
<!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>Student Details</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Roll Number</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="student in students">
<td>{{ student.name }}</td>
<td>{{ student.rollNumber }}</td>
<td>{{ student.grade }}</td>
</tr>
</tbody>
</table>
<script>
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
// Sample student data (you can replace this with your actual data)
$scope.students = [
{ name: 'Alice', rollNumber: '101', grade: 'A' },
{ name: 'Bob', rollNumber: '102', grade: 'B' },
{ name: 'Charlie', rollNumber: '103', grade: 'C' },
// Add more student objects here...
];
});
</script>
</body>
</html>
Assignment no: 7
Using angular js Create a SPA that show Syllabus content of all subjects of MSC(CS)
Sem II (use ng-view)
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-
route.min.js"></script>
</head>
<body>
<h1>MSC (CS) Semester II Syllabus</h1>
<p><a href ="#subject1">Design and Analsis of Algorithm</a></p>
<p><a href ="#subject2">Full Stack Development</a></p>
<div ng-view></div>
<script>
angular.module('myApp', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/subject1', {
templateUrl: 'subject1.html',
controller: 'Subject1Controller'
})
.when('/subject2', {
templateUrl: 'subject2.html',
controller: 'Subject2Controller'
})
// Add more routes for other subjects
.otherwise({
redirectTo: '/subject1' // Default route
});
})
.controller('Subject1Controller', function ($scope) {
// Load syllabus data for subject 1
// Example: $scope.syllabus = getSubject1Syllabus();
})
.controller('Subject2Controller', function ($scope) {
// Load syllabus data for subject 2
// Example: $scope.syllabus = getSubject2Syllabus();
});
</script>
</body>
</html>
Output:
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>
</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>
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).
<!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"
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:
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) {
$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">
{{ 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:
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');
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}`);
}
});
}
});
});
// 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');
} 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:
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();
}
}).listen(3000);
Output:
Before
After submitting
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!');
});
});
});
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:
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:
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}`);
});
});
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:
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 }));
// 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}`);
});
Output:
Before login:
After login:
Assignment no: 22
Write node js script to interact with the file system, and serve a web page from a File
// File: server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 8080;
http.createServer((req, res) => {
// Read the HTML file (index.html)
const filePath = path.join(__dirname, 'sample.html');
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error reading file');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
}).listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Output:

More Related Content

What's hot

Sop izin keluar masuk kawasan
Sop izin keluar masuk kawasanSop izin keluar masuk kawasan
Sop izin keluar masuk kawasanBenny Benny
 
Administrasi Server
Administrasi ServerAdministrasi Server
Administrasi ServerlombkTBK
 
PPT RAPAT ORANG TUA XI TEKNIK.pptx
PPT RAPAT ORANG TUA XI TEKNIK.pptxPPT RAPAT ORANG TUA XI TEKNIK.pptx
PPT RAPAT ORANG TUA XI TEKNIK.pptxfitri nurani
 
Abinul Jawaban Tugas Diklat PBJ Modul 6.pdf
Abinul Jawaban Tugas Diklat PBJ Modul 6.pdfAbinul Jawaban Tugas Diklat PBJ Modul 6.pdf
Abinul Jawaban Tugas Diklat PBJ Modul 6.pdfABINUL HAKIM
 
[Pycon KR 2017] Rst와 함께하는 Python 문서 작성 & OpenStack 문서 활용 사례
[Pycon KR 2017] Rst와 함께하는 Python 문서 작성 & OpenStack 문서 활용 사례[Pycon KR 2017] Rst와 함께하는 Python 문서 작성 & OpenStack 문서 활용 사례
[Pycon KR 2017] Rst와 함께하는 Python 문서 작성 & OpenStack 문서 활용 사례Ian Choi
 
Provisioning on Libvirt with Foreman
Provisioning on Libvirt with ForemanProvisioning on Libvirt with Foreman
Provisioning on Libvirt with ForemanNikhil Kathole
 

What's hot (8)

Sop izin keluar masuk kawasan
Sop izin keluar masuk kawasanSop izin keluar masuk kawasan
Sop izin keluar masuk kawasan
 
Administrasi Server
Administrasi ServerAdministrasi Server
Administrasi Server
 
PPT RAPAT ORANG TUA XI TEKNIK.pptx
PPT RAPAT ORANG TUA XI TEKNIK.pptxPPT RAPAT ORANG TUA XI TEKNIK.pptx
PPT RAPAT ORANG TUA XI TEKNIK.pptx
 
Kluster 3
Kluster 3Kluster 3
Kluster 3
 
Abinul Jawaban Tugas Diklat PBJ Modul 6.pdf
Abinul Jawaban Tugas Diklat PBJ Modul 6.pdfAbinul Jawaban Tugas Diklat PBJ Modul 6.pdf
Abinul Jawaban Tugas Diklat PBJ Modul 6.pdf
 
[Pycon KR 2017] Rst와 함께하는 Python 문서 작성 & OpenStack 문서 활용 사례
[Pycon KR 2017] Rst와 함께하는 Python 문서 작성 & OpenStack 문서 활용 사례[Pycon KR 2017] Rst와 함께하는 Python 문서 작성 & OpenStack 문서 활용 사례
[Pycon KR 2017] Rst와 함께하는 Python 문서 작성 & OpenStack 문서 활용 사례
 
Permendagri No. 46 Tahun 2008
Permendagri No. 46 Tahun 2008Permendagri No. 46 Tahun 2008
Permendagri No. 46 Tahun 2008
 
Provisioning on Libvirt with Foreman
Provisioning on Libvirt with ForemanProvisioning on Libvirt with Foreman
Provisioning on Libvirt with Foreman
 

Similar to full stack practical assignment msc cs.pdf

javascript.pptx
javascript.pptxjavascript.pptx
javascript.pptxhasiny2
 
WEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bcaWEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bcaYashKoli22
 
YASH HTML CODES
YASH HTML CODESYASH HTML CODES
YASH HTML CODESYashKoli22
 
YASH HTML CODE
YASH HTML CODE YASH HTML CODE
YASH HTML CODE YashKoli22
 
Html basics 11 form validation
Html basics 11 form validationHtml basics 11 form validation
Html basics 11 form validationH K
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation TechniqueMorshedul Arefin
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling WebStackAcademy
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysqlKnoldus Inc.
 
Web topic 22 validation on web forms
Web topic 22  validation on web formsWeb topic 22  validation on web forms
Web topic 22 validation on web formsCK Yang
 
Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiNaveen Kumar Veligeti
 
ASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseChristopher Singleton
 
Christopher Latham Portfolio
Christopher Latham PortfolioChristopher Latham Portfolio
Christopher Latham Portfoliolathamcl
 
KLab 2019 Meetup - TypeScript come (forse) non lo hai mai visto
KLab 2019 Meetup - TypeScript come (forse) non lo hai mai vistoKLab 2019 Meetup - TypeScript come (forse) non lo hai mai visto
KLab 2019 Meetup - TypeScript come (forse) non lo hai mai vistoGianluca Carucci
 
The Django Book - Chapter 7 forms
The Django Book - Chapter 7 formsThe Django Book - Chapter 7 forms
The Django Book - Chapter 7 formsVincent Chien
 

Similar to full stack practical assignment msc cs.pdf (20)

javascript.pptx
javascript.pptxjavascript.pptx
javascript.pptx
 
WEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bcaWEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bca
 
YASH HTML CODES
YASH HTML CODESYASH HTML CODES
YASH HTML CODES
 
YASH HTML CODE
YASH HTML CODE YASH HTML CODE
YASH HTML CODE
 
Html basics 11 form validation
Html basics 11 form validationHtml basics 11 form validation
Html basics 11 form validation
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
 
assignment 8.pdf
assignment 8.pdfassignment 8.pdf
assignment 8.pdf
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
 
Web topic 22 validation on web forms
Web topic 22  validation on web formsWeb topic 22  validation on web forms
Web topic 22 validation on web forms
 
Javascript
JavascriptJavascript
Javascript
 
Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligeti
 
ASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server Database
 
Christopher Latham Portfolio
Christopher Latham PortfolioChristopher Latham Portfolio
Christopher Latham Portfolio
 
Chat php
Chat phpChat php
Chat php
 
Java script
Java scriptJava script
Java script
 
forms.pptx
forms.pptxforms.pptx
forms.pptx
 
KLab 2019 Meetup - TypeScript come (forse) non lo hai mai visto
KLab 2019 Meetup - TypeScript come (forse) non lo hai mai vistoKLab 2019 Meetup - TypeScript come (forse) non lo hai mai visto
KLab 2019 Meetup - TypeScript come (forse) non lo hai mai visto
 
wp-UNIT_III.pptx
wp-UNIT_III.pptxwp-UNIT_III.pptx
wp-UNIT_III.pptx
 
The Django Book - Chapter 7 forms
The Django Book - Chapter 7 formsThe Django Book - Chapter 7 forms
The Django Book - Chapter 7 forms
 

Recently uploaded

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

full stack practical assignment msc cs.pdf

  • 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; } }
  • 6. </script> </head> <body> <h2>EMPLOYEE REGISTRATION FORM</h2> <form name="employeeForm" onsubmit="return validateForm()"> <label for="dob">Date of Birth:</label> <input type="date" id="dob" required><br> <label for="joining-date">Joining Date:</label> <input type="date" id="joining-date" required><br> <label for="salary">Salary:</label> <input type="number" id="salary" min="1" step="any" required><br> <input type="submit" value="Register"> </form> </body> </html> Output:
  • 7. Assignment no: 3 Create an HTML form for Login and write a JavaScript to validate email ID using Regular Expression. <!DOCTYPE html> <html lang="en"> <head> <title>Login Form</title> <script type="text/javascript"> function validateEmail() { var email = document.querySelector("#email").value; var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/; if (!emailPattern.test(email)) { alert("Please enter a valid email address."); return false; } return true; } function validateForm() { var isValidEmail = validateEmail(); if (isValidEmail) { alert("Login successful!"); return true; } else { alert("Invalid email address."); return false; } } </script> </head> <body> <h2>LOGIN FORM</h2> <form name="loginForm" onsubmit="return validateForm()"> <label for="email">Email:</label> <input type="email" id="email" required><br> <input type="submit" value="Login"> </form> </body> </html> Output:
  • 8. Assignment no: 4 Write angular JS by using ng-click Directive to display an alert message after clicking the element <!DOCTYPE html> <html lang="en"> <head> <title>Login Form</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head> <body ng-app="myApp"> <h2>LOGIN FORM</h2> <div ng-controller="LoginController"> <label for="email">Email:</label> <input type="email" id="email" ng-model="userEmail" required><br> <button ng-click="showAlert()">Login</button> </div> <script> angular.module('myApp', []) .controller('LoginController', function ($scope) { $scope.showAlert = function () { alert('Login successful!'); // Display an alert message }; }); </script> </body> </html> Output:
  • 9. Assignment no: 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. <!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>Calculator</h2> <p>First Number: <input type="number" ng-model="a" /></p> <p>Second Number: <input type="number" ng-model="b" /></p> <p>Sum: <span ng-bind="a + b"></span></p> <button ng-click="calculateSum()" ng-show="a && b" ng-disabled="!a || !b">Calculate</button> <script> angular.module('myApp', []) .controller('myCtrl', function ($scope) { $scope.calculateSum = function () { $scope.sum = $scope.a + $scope.b; }; }); </script> </body> </html> Output:
  • 10. Assignment no: 6 Using angular js display the 10 student details in Table format (using ng-repeat directive use Array to store data ) <!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>Student Details</h2> <table> <thead> <tr> <th>Name</th> <th>Roll Number</th> <th>Grade</th> </tr> </thead> <tbody> <tr ng-repeat="student in students">
  • 11. <td>{{ student.name }}</td> <td>{{ student.rollNumber }}</td> <td>{{ student.grade }}</td> </tr> </tbody> </table> <script> angular.module('myApp', []) .controller('myCtrl', function ($scope) { // Sample student data (you can replace this with your actual data) $scope.students = [ { name: 'Alice', rollNumber: '101', grade: 'A' }, { name: 'Bob', rollNumber: '102', grade: 'B' }, { name: 'Charlie', rollNumber: '103', grade: 'C' }, // Add more student objects here... ]; }); </script> </body> </html>
  • 12. Assignment no: 7 Using angular js Create a SPA that show Syllabus content of all subjects of MSC(CS) Sem II (use ng-view) <!-- index.html --> <!DOCTYPE html> <html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular- route.min.js"></script> </head> <body> <h1>MSC (CS) Semester II Syllabus</h1> <p><a href ="#subject1">Design and Analsis of Algorithm</a></p> <p><a href ="#subject2">Full Stack Development</a></p> <div ng-view></div> <script> angular.module('myApp', ['ngRoute']) .config(function ($routeProvider) { $routeProvider .when('/subject1', { templateUrl: 'subject1.html', controller: 'Subject1Controller' }) .when('/subject2', { templateUrl: 'subject2.html', controller: 'Subject2Controller' }) // Add more routes for other subjects .otherwise({ redirectTo: '/subject1' // Default route }); }) .controller('Subject1Controller', function ($scope) { // Load syllabus data for subject 1 // Example: $scope.syllabus = getSubject1Syllabus();
  • 13. }) .controller('Subject2Controller', function ($scope) { // Load syllabus data for subject 2 // Example: $scope.syllabus = getSubject2Syllabus(); }); </script> </body> </html> Output:
  • 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}`); });
  • 36. Assignment no: 22 Write node js script to interact with the file system, and serve a web page from a File // File: server.js const http = require('http'); const fs = require('fs'); const path = require('path'); const PORT = 8080; http.createServer((req, res) => { // Read the HTML file (index.html) const filePath = path.join(__dirname, 'sample.html'); fs.readFile(filePath, (err, data) => { if (err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Error reading file'); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(data); } }); }).listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); }); Output: