0% found this document useful (0 votes)
4 views17 pages

HTML JavaScript Form Validation Guide

web tech lab 4 to lab 10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

HTML JavaScript Form Validation Guide

web tech lab 4 to lab 10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Department of Computer Science &Technology

Subject: Web Technology Lab


Subject code: BCS552

Assignment: 4
Aim:- Write programs using HTML and Java Script for validation of input data.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
body {
font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center;
height: 100vh;
margin: 0; background-color: #f3f3f3;
}
.container { width: 400px; padding: 20px; background-color: white; box-shadow: 0 0 10px
rgba(0, 0, 0, 0.1); border-radius: 5px; }
h2 {
text-align: center; color: #333;
}
.form-group { margin-bottom: 15px; } label {
display: block; margin-bottom: 5px; color: #555; } input[type="text"], input[type="email"],
input[type="tel"], input[type="password"] {
width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; }
input[type="submit"] {
width: 100%; padding: 10px; border: none; background-color: #4CAF50; color: white; font-
size: 16px; border-radius: 4px;
cursor: pointer; } input[type="submit"]:hover {
background-color: #45a049;
}
.error { color: red; font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<h2>Registration Form</h2>
<form name="registrationForm" onsubmit="return validateForm()">
<!-- Name Field -->
<div class="form-group">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name">
<div id="nameError" class="error"></div>
</div>
<!-- Email Field -->
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<div id="emailError" class="error"></div>
</div>
<!-- Phone Number Field -->
<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone">
<div id="phoneError" class="error"></div>
</div>
<!-- Password Field -->
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="passwordError" class="error"></div>
</div>
<!-- Submit Button -->
<input type="submit" value="Submit">
</form>
</div>
<script> function validateForm() { // Clear previous error messages
[Link]("nameError").innerText = "";
[Link]("emailError").innerText = "";
[Link]("phoneError").innerText = "";
[Link]("passwordError").innerText = "";
// Retrieve form values const name = [Link]["registrationForm"]["name"].value;
const email = [Link]["registrationForm"]["email"].value; const phone =
[Link]["registrationForm"]["phone"].value; const password =
[Link]["registrationForm"]["password"].value; let isValid = true;
// Validate Name if (name === "") { [Link]("nameError").innerText =
"Name is required."; isValid = false;
} else if ([Link] < 3) { [Link]("nameError").innerText = "Name
must be at least 3
characters long."; isValid = false;
}
// Validate Email
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (email === "") { [Link]("emailError").innerText = "Email is
required."; isValid = false;
} else if (![Link](email)) { [Link]("emailError").innerText =
"Enter a valid email address."; isValid = false;
}
// Validate Phone Number const phonePattern = /^[0-9]{10}$/;
if (phone === "") { [Link]("phoneError").innerText = "Phone number is
required."; isValid = false;
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

} else if (![Link](phone)) { [Link]("phoneError").innerText =


"Enter a valid 10-digit phone
number."; isValid = false;
}
// Validate Password if (password === "") {
[Link]("passwordError").innerText = "Password is required."; isValid =
false;
} else if ([Link] < 6) { [Link]("passwordError").innerText =
"Password must be at least
6 characters long."; isValid = false;
}
return isValid; // Prevent form submission if validation fails }
</script>
</body>
</html>
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

Assignment: 5
Aim:- Write a program in XML for creation of DTD, which specifies set of rules. Create a
style sheet in CSS/ XSL & display the document in internet explorer.

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "[Link]">
<?xml-stylesheet type="text/css" href="[Link]"?>
<books>
<book>
<title>Learning XML</title>
<author>John Doe</author>
<publisher>OpenAI Publishing</publisher>
<price>29.99</price>
</book>
<book>
<title>Advanced HTML</title>
<author>Jane Smith</author>
<publisher>Tech Books</publisher>
<price>39.95</price>
</book>
</books>

[Link]
<!ELEMENT books (book+)>
<!ELEMENT book (title, author, publisher, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT price (#PCDATA)>
[Link]
/* Styling for the entire books list */
books {
display: block; font-family: Arial, sans-serif;
margin: 20px; padding: 20px; border: 1px solid #ddd; background-color: #f9f9f9;
}
book {
display: block; margin-bottom: 15px; padding: 10px;
border-bottom: 1px solid #ccc;
}
title {
font-size: 20px; font-weight: bold; color: #333;
}
author, publisher, price { display: block; margin-top: 5px; font-size: 14px; color: #555;
}
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

Assignment 6:
Aim:- Create a Java Bean for Employee information (EmpID, Name, Salary, Designation
and Department):

import [Link];

public class Employee implements Serializable {


// Private fields private
int empID; private String
name; private double
salary; private String
designation; private
String department;

// No-argument constructor
public Employee() {
}

// Getters and Setters

public int getEmpID() {


return empID;
}

public void setEmpID(int empID) {


[Link] = empID;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


[Link] = salary;
}

public String getDesignation() {


return designation;
}
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

public void setDesignation(String designation) {


[Link] = designation;
}

public String getDepartment() {


return department;
}

public void setDepartment(String department) {


[Link] = department;
}

// Optional: Override toString method for easy display


@Override public
String toString()
{ return "Employee{" +
"empID=" + empID +
", name='" + name + '\'' +
", salary=" + salary +
", designation='" + designation + '\'' +
", department='" + department + '\'' +
'}';
}
}
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

Assignment: 7
Aim:- Build a command-line utility using [Link] that performs a specific task, such as
converting text to uppercase, calculating the factorial of a number, or generating
random passwords. #!/usr/bin/env node

const { program } = require('commander');


const crypto = require('crypto');

// Utility function to generate a random password


function generatePassword(length, useNumbers, useSpecialChars) {
const alphabet =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numbers = "0123456789";
const specialChars = "!@#$%^&*()_+~`|}{[]:;?><,./-=";
let characters = alphabet; if (useNumbers)
characters += numbers; if (useSpecialChars)
characters += specialChars;

let password = ''; for (let i =


0; i < length; i++) {
const randomIndex = [Link](0, [Link]);
password += characters[randomIndex];
}
return password;
}

// Command-line options
program
.version('1.0.0')
.description('Generate a random password')
.option('-l, --length <number>', 'length of password', '12')
.option('-n, --numbers', 'include numbers', false)
.option('-s, --special', 'include special characters',
false) .parse([Link]); const options =
[Link]();

// Generate password based on user input const length =


parseInt([Link], 10);
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

const password = generatePassword(length,[Link],


[Link]); [Link](`Generated Password: ${password}`);
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

Assignment: 8
Aim:- Develop a script that uses MongoDB's aggregation framework to perform operations
like grouping, filtering, and sorting. For instance, aggregate user data to find the average

age of users in different cities. const { MongoClient } = require('mongodb');

async function runAggregation() { const uri = "mongodb://localhost:27017"; //


MongoDB connection URI const client = new MongoClient(uri, { useNewUrlParser:
true, useUnifiedTopology: true });

try { await
[Link]();
[Link]("Connected to MongoDB!");
// Specify the database and collection const
database = [Link]("mydatabase"); const
usersCollection = [Link]("users");

// Aggregation pipeline
const pipeline = [
{
$group: {
_id: "$city",
averageAge: { $avg: "$age" },
userCount: { $sum: 1 }
}
},
{
$sort: { averageAge: -1 } // Sort cities by average age in descending order
},
{
$match: { userCount: { $gte: 5 } } // Optional: Filter to show only cities with at
least 5 users
}
];

// Execute the aggregation const results = await


[Link](pipeline).toArray();

[Link]("Average age by city:"); [Link](result => { [Link](`City: $


{result._id}, Average Age: ${[Link](2)}, User Count: $
{[Link]}`);
});

} catch (err) { [Link]("Error running


aggregation:", err);
} finally { await
[Link]();
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

}
} runAggregation().catch([Link]);
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

Assignment: 9

Aim:- Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2,
pwd3 and pwd4 respectively. Write a servlet for doing the following: 1. Create a Cookie and
add these four user id’s and passwords to this Cookie. 2. Read the user id and passwords
entered in the Login form and authenticate with the values available in the cookies.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login Form</h2>
<form action="LoginServlet" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

[Link] import
[Link]; import
[Link];
import [Link].*; import
[Link]; import
[Link]; import
[Link]; import [Link];

@WebServlet("/LoginServlet") public class


LoginServlet extends HttpServlet {

// Hardcoded users and passwords private static final Map<String,


String> users = new HashMap<>();

static {
[Link]("user1", "pwd1");
[Link]("user2", "pwd2");
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

[Link]("user3", "pwd3");
[Link]("user4", "pwd4");
}

@Override
public void init() throws ServletException {
// Creating a cookie with all user data
StringBuilder cookieValue = new StringBuilder(); for
([Link]<String, String> entry : [Link]()) {

[Link]([Link]()).append("=").append([Link]()).append(";");
}
// Adding the cookie
Cookie userCookie = new Cookie("userAuth", [Link]());
[Link](60 * 60 * 24); // Cookie expires in one day
[Link](true); // Make it HTTP-only for security

// Add the cookie when the servlet initializes


getServletContext().setAttribute("userCookie", userCookie);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get username and password from request
String username = [Link]("username");
String password = [Link]("password");

// Retrieve the stored cookie


Cookie[] cookies =
[Link](); Cookie
userCookie = null; for (Cookie cookie :
cookies) {
if ([Link]().equals("userAuth")) {
userCookie = cookie;
break;
}
}

// Check if cookie exists and authenticate the


user boolean isAuthenticated = false; if
(userCookie != null) {
String[] usersData = [Link]().split(";");
for (String userData : usersData)
{ String[] parts = [Link]("=");
if (parts[0].equals(username) && parts[1].equals(password)) {
isAuthenticated = true;
break;
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

}
}
}

// Prepare response [Link]("text/html");

PrintWriter out = [Link]();


if (isAuthenticated) {
[Link]("<h2>Login Successful</h2>");
[Link]("<p>Welcome, " + username + "!</p>");
} else { [Link]("<h2>Login
Failed</h2>");
[Link]("<p>Invalid username or
password.</p>"); }
}
}
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

Assignment: 10
Aim:- Create a table which should contain at least the following fields: name, password,
email-id, phone number Write Servlet/JSP to connect to that database and extract data from
the tables and display them. Insert the details of the users who register with the web site,
whenever a new user clicks the submit button in the registration page.
Set up database :
CREATE DATABASE UserDB;

USE UserDB;

CREATE TABLE Users ( id INT


AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(50) NOT NULL, password
VARCHAR(255) NOT NULL, email
VARCHAR(100) NOT NULL UNIQUE, phone
VARCHAR(15) NOT NULL
);
[Link]:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
</head>
<body>
<h2>Register</h2>
<form action="RegisterServlet" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>

<label for="phone">Phone Number:</label>


<input type="text" id="phone" name="phone" required><br><br>

<input type="submit" value="Register">


</form>
</body>
</html>

[Link]: import
[Link]; import
Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

[Link];
import [Link].*; import
[Link]; import
[Link]; import [Link].*;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/UserDB";
private static final String JDBC_USERNAME = "root"; private
static final String JDBC_PASSWORD = "yourpassword";

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get form data
String name = [Link]("name");
String password = [Link]("password");
String email = [Link]("email");
String phone = [Link]("phone");

Connection conn = null;


PreparedStatement pstmt = null;
ResultSet rs = null;

[Link]("text/html");
PrintWriter out = [Link]();

try {
// Load JDBC driver
[Link]("[Link]");

// Connect to the database


conn = [Link](JDBC_URL, JDBC_USERNAME,
JDBC_PASSWORD);

// Insert new user into the database


String insertSQL = "INSERT INTO Users (name, password, email, phone) VALUES
(?, ?, ?, ?)"; pstmt =
[Link](insertSQL);
[Link](1, name);
[Link](2, password);
[Link](3, email);
[Link](4, phone);
[Link]();

// Retrieve all users from the database


Department of Computer Science &Technology
Subject: Web Technology Lab
Subject code: BCS552

String selectSQL = "SELECT * FROM


Users"; pstmt =
[Link](selectSQL); rs =
[Link]();

// Display all users


[Link]("<h2>Registered Users</h2>");
[Link]("<table
border='1'><tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th></tr>");

while ([Link]()) { [Link]("<tr>");


[Link]("<td>" + [Link]("id") + "</td>");
[Link]("<td>" + [Link]("name") +
"</td>"); [Link]("<td>" + [Link]("email")
+ "</td>"); [Link]("<td>" +
[Link]("phone") + "</td>");
[Link]("</tr>");
}
[Link]("</table>");

} catch (Exception e)
{ [Link]("Error: " +
[Link]());
[Link]();
} finally {
// Clean up database resources try { if (rs != null) [Link](); } catch (SQLException e)
{ [Link](); } try { if (pstmt != null) [Link](); } catch (SQLException
e) { [Link](); } try { if (conn != null) [Link](); } catch (SQLException
e) { [Link](); }
}
}
}

You might also like