You are on page 1of 29

1. Write a JavaScript function that reverse a number.

function reverse() {
var r,rev=0,n;
n = parseInt(prompt("enter a number:"));
while (n != 0) {
r = n % 10;
rev = rev * 10 + r;
n = parseInt(n / 10);
}
document.write("reverse of number is:"+rev);
}
OUTPUT:

2. Write a JavaScript function that checks whether a passed string is palindrome or not?
function palin()
{
var a,no,b,temp=0;
no=Number(document.getElementById("no_input").value);
b=no;
while(no>0)
{
a=no%10;
no=parseInt(no/10);
temp=temp*10+a;
}
if(temp==b) {alert("Palindrome number");}
else {alert("Not Palindrome number");}
}
OUTPUT:

3. Write a JavaScript function that accepts a string as a parameter and converts the first
letter of each word of the string in upper case.
function uppercase(str) {
var array1 = str.split(' ');
var newarray1 = []
for (var x = 0; x < array1.length; x++) {
newarray1.push(array1[x].charAt(0).toUpperCase() + array1[x].slice(1));}
return newarray1.join(' ');}
console.log(uppercase("my name is ayush"));
OUTPUT:

4. Write a JavaScript function that accepts a string as a parameter and counts the number
of vowels within the string.
function countVowels(str) {
str = str.toLowerCase();
const vowels = ['a', 'e', 'i', 'o', 'u'];
let count = 0;
for (let char of str) {
// Check if the character is a vowel
if (vowels.includes(char)) {
count++;
}
}
return count;
}
const str = "Hello World";
console.log("Number of vowels:", countVowels(str));
OUTPUT:

5. Write a JavaScript function that accepts a number as a parameter and check the number
is prime or not.
function isPrime(num) {
if (num <= 1) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) { return false; }
}
return true;
}
const number = 17;
if (isPrime(number)) {
console.log(number + " is prime.");
} else {
console.log(number + " is not prime.");}
OUTPUT:

6. Write a JavaScript function which accepts an argument and returns the type.
function getType(arg) {
return typeof arg;
}
console.log(getType(5));
console.log(getType("Hello"));
console.log(getType(true));
console.log(getType([]));
console.log(getType({}));
console.log(getType(null));
console.log(getType(undefined));
OUTPUT:

7. Write a JavaScript function which will take an array of numbers stored and find the
second lowest and second greatest numbers, respectively.
function findSecondLowestAndGreatest(arr) {
const sortedArr = [...new Set(arr)].sort((a, b) => a - b);
if (sortedArr.length < 2) {
return "Array should contain at least two distinct numbers.";
}
const secondLowest = sortedArr[1];
const secondGreatest = sortedArr[sortedArr.length - 2];

return {
secondLowest: secondLowest,
secondGreatest: secondGreatest
};
}
const numbers = [10, 5, 3, 8, 15, 8, 3, 10];
const result = findSecondLowestAndGreatest(numbers);
console.log("Second lowest number:", result.secondLowest);
console.log("Second greatest number:", result.secondGreatest);
OUTPUT:
8. Write a JavaScript function to check whether an `input` is an array or not
console.log(is_array('subash')); console.log(is_array([1, 2, 4, 0]));

function is_array(input) {
return Array.isArray(input);
}
console.log(is_array('subash'));
console.log(is_array([1, 2, 4, 0]));
OUTPUT:

9. Write a simple JavaScript program to join all elements of the following array into a
string.
const array = ['apple', 'banana', 'orange', 'grape'];
const joinedString = array.join(', ');
console.log(joinedString);
OUTPUT:

10. Write a JavaScript function to check whether an `input` is a date object or not.
function isDate(input) {
return input instanceof Date;
}
console.log(isDate(new Date()));
console.log(isDate('2023-12-31'));
OUTPUT:

11. Write a JavaScript function to check whether an `input` is a string or not


function isString(input) {
return typeof input === 'string';
}
console.log(isString('hello'));
console.log(isString(123));
console.log(isString(true));
OUTPUT:
12. Write a JavaScript program to list the properties of a JavaScript object.
const person = {
firstName: 'John',
lastName: 'Cena',
age: 47,
email: 'youcanseeme@sike.com'
};
function listProperties(obj) {
for (let property in obj) {
if (obj.hasOwnProperty(property)) {
console.log(property);
}
}
}
console.log("Properties of the 'person' object:");
listProperties(person);
OUTPUT:

13. Write a JavaScript program to delete the rollno property from the following object.
Also print the object before or after deleting the property.
var student = {name : "David Ray”, class : "VI”, Roll no : 12 };

var student = {
name: "David Rayy",
sclass: "VI",
rollno: 12
};
console.log("Object before deleting 'rollno' property:");
console.log(student);
if ('rollno' in student) {
delete student.rollno;
}
console.log("\nObject after deleting 'rollno' property:");
console.log(student);
OUTPUT:
14. Write a JavaScript program to get the length of a JavaScript object.
Sample object :
var student = {name : "David Ray”, class : "VI”, Roll no : 12 };
var student = {
name: "David Rayy",
sclass: "VI",
rollno: 12
};
var lengthOfObject = Object.keys(student).length;
console.log("Length of the object:", lengthOfObject);
OUTPUT:

15. Write a JavaScript program of window object such as alert(), prompt(), confirm(),
open(), close()
alert("This is an alert message!");
var userInput = prompt("Please enter your name:", "John Doe");
if (userInput !== null) {
alert("Hello, " + userInput + "!");
} else {
alert("You cancelled the prompt.");
}
var userResponse = confirm("Are you sure you want to proceed?");
if (userResponse) {
alert("You clicked OK!");
} else {
alert("You clicked Cancel!");
}
var newWindow = window.open("https://www.fb.com", "_blank");
OUTPUT:
16. Write a JavaScript program in String object
1) By string literal
var strLiteral = "Hello, world!";
console.log("String created using string literal:", strLiteral);
2) By string object (using new keyword)
var strObject = new String("Hello, world!");
console.log("String created using string object:", strObject);
17. Write a JavaScript program in Boolean object such as toString, valueof.
var boolObj = new Boolean(true);
console.log("Boolean object:", boolObj);
console.log("Type of boolObj:", typeof boolObj);
var boolString = boolObj.toString();
console.log("Boolean object converted to string:", boolString);
console.log("Type of boolString:", typeof boolString);
var boolValue = boolObj.valueOf();
console.log("Primitive value of Boolean object:", boolValue);
console.log("Type of boolValue:", typeof boolValue);
OUTPUT:

18. Write a JavaScript program in RegExp object such as exec(), toString() method.
var pattern = /[a-z]+/g;
var testString = "Hello World! This is a test string.";
var match;
while ((match = pattern.exec(testString)) !== null) {
console.log("Match found:", match[0]);
console.log("Index:", match.index);
}
var patternString = pattern.toString();
console.log("Regular expression as string:", patternString);
OUTPUT:
19. Write a JavaScript program to create a form using following fields:
a. user-name b. password c. email d. address e. phone number
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration Form</title>
<style>
label {
display: block;
margin-bottom: 10px;
}
input {
margin-bottom: 10px;
}
#submitBtn {
margin-top: 10px;
}
</style>
</head>
<body>
<h2>User Registration Form</h2>
<form id="registrationForm">
<label for="userName">User Name:</label>
<input type="text" id="userName" required>

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

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

<label for="address">Address:</label>
<textarea id="address" rows="4" required></textarea>

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


<input type="tel" id="phoneNumber" pattern="[0-9]{10}" required>

<button type="submit" id="submitBtn">Submit</button>


</form>

<script>
document.getElementById('registrationForm').addEventListener('submit',
function(event) {
event.preventDefault();
var userName = document.getElementById('userName').value;
var password = document.getElementById('password').value;
var email = document.getElementById('email').value;
var address = document.getElementById('address').value;
var phoneNumber = document.getElementById('phoneNumber').value;
console.log("User Name:", userName);
console.log("Password:", password);
console.log("Email:", email);
console.log("Address:", address);
console.log("Phone Number:", phoneNumber);
});
</script>
</body>
</html>

OUTPUT:

20. Create a HTML form with fields like username, password, email, country. The username
should be textbox, password and email should be the password and email fields. The country should be
drop down. Now write JavaScript function for form validation. Your function should validate the
username to be of length 5, password should start with digit and should be alphanumeric. The email
should be valid. The country field should be selected.

<!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>
label {
display: block;
margin-bottom: 5px;
}
input, select {
margin-bottom: 10px;
}
#submitBtn {
margin-top: 10px;
}
.error {
color: red;
}
</style>
</head>
<body>
<h2>Form Validation</h2>
<form id="registrationForm" onsubmit="return validateForm()">
<label for="username">Username:</label>
<input type="text" id="username" required>

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

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

<label for="country">Country:</label>
<select id="country" required>
<option value="">Select Country</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="Australia">Australia</option>
</select>

<button type="submit" id="submitBtn">Submit</button>


</form>
<script>
function validateForm() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var email = document.getElementById('email').value;
var country = document.getElementById('country').value;
var isValid = true;
var errorMessages = [];
if (username.length < 5) {
isValid = false;
errorMessages.push("Username must be at least 5 characters long.");
}
if (!/^\d/.test(password) || !/^[a-zA-Z0-9]+$/.test(password)) {
isValid = false;
errorMessages.push("Password must start with a digit and be
alphanumeric.");
}
if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
isValid = false;
errorMessages.push("Invalid email format.");
}
if (country === "") {
isValid = false;
errorMessages.push("Please select a country.");
}
if (!isValid) {
alert(errorMessages.join("\n"));
}

return isValid;
}
</script>
</body>
</html>

OUTPUT:

21. Write a JavaScript program to use events such asclickevent(), mouseoverevent0, focusevent().
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling</title>
<style>
#myButton {
padding: 10px 20px;
font-size: 16px;
background-color: #3498db;
color: white;
border: none;
cursor: pointer;
margin-right: 10px;
}
#myInput {
padding: 10px;
font-size: 16px;
}
</style>
</head>
<body>
<h2>Event Handling</h2>
<button id="myButton">Click Me!</button>
<input type="text" id="myInput" placeholder="Enter your name">

<script>
document.getElementById('myButton').addEventListener('click', function() {
alert('Button clicked!');
});
document.getElementById('myButton').addEventListener('mouseover', function()
{
this.style.backgroundColor = '#2980b9';
});
document.getElementById('myButton').addEventListener('mouseout', function() {
this.style.backgroundColor = '#3498db';
});
document.getElementById('myInput').addEventListener('focus', function() {
this.style.border = '2px solid #2ecc71';
});

document.getElementById('myInput').addEventListener('blur', function() {
this.style.border = '2px solid #e74c3c';
});
</script>
</body>
</html>

OUTPUT:

22. Write a JavaScript program to show the Event handler property.

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handler Property</title>
</head>
<body>
<h2>Event Handler Property</h2>
<button id="myButton">Click Me!</button>
<script>
var button = document.getElementById('myButton');
button.onclick = function() {
alert('Button clicked using event handler property!');
};
console.log("Event handler property of the button:", button.onclick);
</script>
</body>
</html>

OUTPUT:

23. Write a JavaScript program to use of error handling mechanism using:

a) try-catch finally block


try {
var x = y;
} catch (error) {
console.log("An error occurred:", error.message);
} finally {
console.log("Finally block executed.");
}
OUTPUT:

b) try-throw catch

try {
var num = 5;
if (num > 10) {
throw "Number is too large";
}
console.log("Number is within acceptable range.");
} catch (error) {
console.log("An error occurred:", error);
}

OUTPUT:

24. Write a JavaScript program to create a Cookie.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Cookie</title>
</head>
<body>
<h2>Create Cookie</h2>
<button onclick="createCookie()">Create Cookie</button>
<script>
function createCookie() {
var name = "username";
var value = "john";
var days = 7;
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
} else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";

alert("Cookie 'username' with value 'john' has been created and will expire
in 7 days.");
}
</script>
</body>
</html>

OUTPUT:

25. Write a JavaScript program to read a cookie.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Read Cookie</title>
</head>
<body>
<h2>Read Cookie</h2>
<button onclick="readCookie()">Read Cookie</button>
<script>
function readCookie() {
var cookies = document.cookie.split(';');

var cookieValue = null;


for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.startsWith("username=")) {
cookieValue = cookie.substring("username=".length, cookie.length);
break;
}
}
if (cookieValue) {
alert("Value of 'username' cookie: " + cookieValue);
} else {
alert("Cookie 'username' not found.");
}
}
</script>
</body>
</html>

OUTPUT:

26. Write a JavaScript program to Change a Cookie.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Cookie</title>
</head>
<body>
<h2>Change Cookie</h2>
<button onclick="changeCookie()">Change Cookie</button>
<script>
function changeCookie() {
var name = "username";
var newValue = "smith";
var days = 7;
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toUTCString();
document.cookie = name + "=" + newValue + expires + "; path=/";
alert("Cookie 'username' has been changed to 'smith' and will expire in 7
days.");}
</script>
</body>
</html>
OUTPUT:
27. Write a JavaScript program to Delete a Cookie.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete Cookie</title>
</head>
<body>
<h2>Delete Cookie</h2>
<button onclick="deleteCookie()">Delete Cookie</button>
<script>
function deleteCookie() {
var name = "username";
var expires = "expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
document.cookie = name + "=;" + expires;
alert("Cookie 'username' has been deleted.");
}
</script>
</body>
</html>
OUTPUT:

28. Write a JavaScript program to use of AJAX.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Example</title>
<script>
function fetchData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML=this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</head>
<body>
<h2>AJAX Example</h2>
<button onclick="fetchData()">Fetch Data</button>
<div id="data"></div>
</html>
OUTPUT:

29. Write a JavaScript program to use of JQUERY.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Selectors Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>jQuery Selectors Example</h1>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<script>
$("p").css("color", "blue");
</script>
<p class="myClass">This paragraph has the class "myClass".</p>
<script>
$(".myClass").css("font-weight", "bold");
</script>
<p id="myID">This paragraph has the ID "myID".</p>
<script>
$("#myID").css("text-decoration", "underline");
</script>
<a href="https://www.example.com">Click here</a> to go to the Example
website.
<script>
$("a[href='https://www.example.com']").css("color", "red");
</script>
</body>
</html>
OUTPUT:

30. Write a HTML script containing use of media query for changing the background-color of html page
to black if the viewport is 600 pixels wide or more than that otherwise if the viewport is less than 500
pixels, the background-color should be changed to red.

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Media Query Example</title>
<style>
body {
background-color: red;
margin: 0;
padding: 0;
}
@media screen and (min-width: 600px) {
body {
background-color: black;
}
}
</style>
</head>
<body>
<h2>Media Query Example</h2>
<p>The background color of this page changes based on the viewport width.</p>
</body>
</html>
OUTPUT:

31. How positioning of HTML elements can be done using CSS? Create a HTML page with a div with some
content and two paragraph with some contents having id p1 and p2. Write external CSS for the div tag
having fixed position with border style solid and width 2 px. The p1 should have relative position. The
font type of p1 should be Arial and color should be red. The p2 have absolute position with top 0px and
left 200px.

HTML File

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Positioning HTML Elements</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="container">
<p id="p1">This is paragraph 1 with relative position.</p>
<p id="p2">This is paragraph 2 with absolute position.</p>
</div>
</body>
</html>
CSS File

#container {
position: fixed;
border: 2px solid black;
padding: 10px;
}
#p1 {
position: relative;
font-family: Arial;
color: red;
}
#p2 {
position: absolute;
top: 0px;
left: 200px;
}

OUTPUT:

32. Create a HTML page with tags header, article and footer. Insert alink containing mail
to info@iost.edu.np in the footer tag. Set the keywords "iost", "csit" using Meta tag in the page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="iost, csit"> <!-- Meta tags for keywords -->
<title>Sample HTML Page</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header, footer {
background-color: #333;
color: #fff;
padding: 10px;
text-align: center;
}
article {
padding: 20px;
}
footer a {
color: #fff;
text-decoration: none;
}
footer a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<header>
<h1>Header Section</h1>
</header>

<article>
<h2>Article Section</h2>
<p>This is the main content of the article section.</p>
</article>

<footer>
<p>Contact us via email: <a
href="mailto:info@iost.edu.np">info@iost.edu.np</a></p>
</footer>
</body>
</html>
OUTPUT:

33. Consider a HTML page contains two divisions and one paragraph tags. The divisions have id div1 and
div2 respectively. The color of text in both of the divisions should be red and background color of the
divisions should be green. The font style in paragraph should be Arial and the size of font should be 14.
Write necessary CSS for the given scenario and debug the web.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample HTML Page</title>
<style>
#div1, #div2 {
color: red;
background-color: green;
padding: 10px;
}
p {
font-family: Arial, sans-serif;
font-size: 14px;
}
</style>
</head>
<body>
<div id="div1">
Content of div1
</div>
<div id="div2">
Content of div2
</div>
<p>
This is a paragraph.
</p>
</body>
</html>
OUTPUT:

34. Create an HTML page titled "MyWebsite" with a Meta tag specifying the author as "John Doe".
Include a div with the ID "content" that contains an unordered list of three cities: Paris, London, and
New York. After London, add a comment saying "Capital of England." Additionally, add a script that
displays an alert saying "Welcome to MyWebsite" when the page loads.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="John F Kennedy">
<title>MyWebsite</title>
</head>
<body>
<div id="content">
<ul>
<li>Paris</li>
<li>London </li>
<li>New York</li>
</ul>
</div>
<script>
window.onload = function() {
alert("Welcome to MyWebsite");
};
</script>
</body>
</html>
OUTPUT:

35. Develop an HTML document titled "Recipes" with a Meta tag indicating the author as "Chef Smith".
Inside a div labeled "recipeList", list three popular dishes: Spaghetti Carbonara, Chicken Tikka Masala,
and Caesar Salad. Link the Chicken Tikka Masala item to a recipe page on www.chickentikkamasala.com.
Following the Caesar Salad item, insert a comment stating "Healthy Option." Trigger an alert displaying
"Enjoy our Recipes!" upon the page's loading.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Chef Smith">
<title>Recipes</title>
</head>
<body>
<div id="recipeList">
<ul>
<li>Spaghetti Carbonara</li>
<li><a href="http://www.chickentikkamasala.com"
target="_blank">Chicken Tikka Masala</a></li>
<li>Caesar Salad
<!-- Healthy Option. -->
</li>
</ul>
</div>
<script>
window.onload = function() {
alert("Enjoy our Recipes!");
};
</script>
</body>
</html>
OUTPUT:

36. Write a JavaScript function named calculateArea that calculates the area of a rectangle. Declare
variables length and width with values 5 and 3 respectively. Print the area using these variables.
function calculateArea(length, width) {
var area = length * width;
console.log("The area of the rectangle is: " + area);
}
var length = 5;
var width = 3;
calculateArea(length, width);
OUTPUT:
37. Develop a JavaScript function named displayInfo that displays information about a user. Declare
variables username with the value "JohnDoe", age with the value 30, and isSubscribed with the value
true. Print the user information using these variables.
function displayInfo(username, age, isSubscribed) {
console.log("Username: " + username);
console.log("Age: " + age);
console.log("Subscribed: " + isSubscribed);
}
var username = "JohnDoe";
var age = 30;
var isSubscribed = true;
displayInfo(username, age, isSubscribed);
OUTPUT:

38. What is client-side form validation? Develop a JavaScript function to validate a username field,
ensuring it contains only letters and numbers and has a length between 4 and 12 characters. Also,
validate a password field, requiring it to have a minimum length of 8 characters and at least one
uppercase letter and one special character.

Client-side form validation refers to the process of validating user input directly within the web
browser using JavaScript before submitting the form to the server. It helps improve user
experience by providing immediate feedback to users about the correctness of their input
without needing to reload the page.
<!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>
</head>
<body>
<h2>User Registration Form</h2>
<form id="registrationForm" onsubmit="return validateForm()">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<input type="submit" value="Submit">
</form>
<p id="errorMessage" style="color: red;"></p>
<script>
function validateForm() {
var usernameField = document.getElementById('username');
var passwordField = document.getElementById('password');
var username = usernameField.value;
var password = passwordField.value;
var usernameRegex = /^[a-zA-Z0-9]{4,12}$/;
var passwordRegex = /^(?=.*[A-Z])(?=.*[!@#$%^&*])(.{8,})$/;
if (!usernameRegex.test(username)) {
showError("Username must contain only letters and numbers and have a
length between 4 and 12 characters.");
return false;
}
if (!passwordRegex.test(password)) {
showError("Password must be at least 8 characters long and contain at
least one uppercase letter and one special character.");
return false;
}
return true;
}
function showError(message) {
var errorMessage = document.getElementById('errorMessage');
errorMessage.textContent = message;
}
</script>
</body>
</html>
OUTPUT:

39. Create an HTML form for product registration. The form should contain fields for the product name,
description, price, and quantity. The price field should only accept numeric values greater than zero, and
the quantity should only accept positive integer values. Write a JavaScript function to validate the form
data before submission.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Registration</title>
</head>
<body>
<h2>Product Registration Form</h2>
<form id="productForm" onsubmit="return validateForm()">
<label for="productName">Product Name:</label>
<input type="text" id="productName" name="productName" required>
<br>
<label for="description">Description:</label>
<textarea id="description" name="description" required></textarea>
<br>
<label for="price">Price:</label>
<input type="number" id="price" name="price" min="0.01" step="0.01"
required>
<br>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" min="1" required>
<br>
<input type="submit" value="Register Product">
</form>
<p id="errorMessage" style="color: red;"></p>
<script>
function validateForm() {
var productName = document.getElementById('productName').value;
var description = document.getElementById('description').value;
var price = document.getElementById('price').value;
var quantity = document.getElementById('quantity').value;
if (isNaN(price) || parseFloat(price) <= 0) {
showError("Price must be a numeric value greater than zero.");
return false;
}
if (!Number.isInteger(parseFloat(quantity)) || parseInt(quantity) <= 0) {
showError("Quantity must be a positive integer value.");
return false;
}
return true;
}
function showError(message) {
var errorMessage = document.getElementById('errorMessage');
errorMessage.textContent = message;
}
</script>
</body>
</html>
OUTPUT:

You might also like