๐Ÿ“˜ JavaScript โ€” Complete Assignment Answers

RMD Sinhgad School of Engineering ยท Dept. of E&TC ยท B.E. Sem-I ยท 2019 Pattern ยท SPPU

Unit I โ€” Intro to JS
Unit II โ€” Data Types
Unit III โ€” Functions & Objects
Unit IV โ€” Regular Expressions
Unit V โ€” DOM & Events
Unit VI โ€” Using JS

Assignment 1 โ€” Introduction to JavaScript

6 Questions ยท CO1

1
What is JavaScript? What are the main features of JavaScript?
CO1
โ–ผ

Definition

JavaScript (JS) is a lightweight, interpreted, object-based scripting language used to make web pages interactive and dynamic. Created by Brendan Eich in 1995, it is one of the three core web technologies alongside HTML and CSS. JS runs in the browser (client-side) without needing server interaction.

Main Features of JavaScript

  1. Interpreted Language โ€” Code is executed line-by-line at runtime; no compilation required.
  2. Object-Based โ€” Supports objects (without full class-based OOP like Java).
  3. Client-Side Scripting โ€” Runs in the browser, reducing load on the server.
  4. Dynamic Typing โ€” Variable types are resolved at runtime (no need to declare types).
  5. Event-Driven โ€” Responds to user actions: clicks, key presses, mouse moves, etc.
  6. Platform Independent โ€” Works on any browser/OS without modification.
  7. Case Sensitive โ€” Var and var are treated differently.
  8. Loosely Typed โ€” Variables can hold any type; no strict declaration needed.
  9. Prototype-Based Inheritance โ€” Objects inherit from other objects via prototype chain.
  10. DOM Manipulation โ€” Can access and modify HTML/CSS elements dynamically.
  11. Supports Closures & First-Class Functions โ€” Functions are treated as values.
// Simple JS example showing features
let name = "Adii";           // Dynamic typing
let age  = 21;
console.log(`Hello, ${name}! Age: ${age}`);

// Object-based
let student = { name: "Adii", branch: "ENTC" };
console.log(student.branch);  // ENTC

// Event-driven
document.getElementById("btn").onclick = function() {
    alert("Button clicked!");
};
2
What are the Event Handlers in JavaScript?
CO1
โ–ผ

Definition

Event handlers are JavaScript functions or code that execute automatically when a specific event occurs on an HTML element. They make web pages interactive by responding to user or browser actions.

How to Assign Event Handlers

  1. Inline HTML attribute: <button onclick="doSomething()">
  2. DOM property: element.onclick = function() {...}
  3. addEventListener(): element.addEventListener("click", fn)

Common Event Handler Categories

CategoryHandlers
Mouse Eventsonclick, ondblclick, onmouseover, onmouseout, onmousedown, onmouseup
Keyboard Eventsonkeydown, onkeyup, onkeypress
Form Eventsonsubmit, onreset, onchange, onfocus, onblur, oninput
Window Eventsonload, onunload, onresize, onscroll
// Method 1: Inline
// <button onclick="alert('Hi!')">Click</button>

// Method 2: DOM property
let btn = document.getElementById("myBtn");
btn.onclick = function() { alert("Clicked!"); };

// Method 3: addEventListener (recommended)
btn.addEventListener("click", function() {
    console.log("Event fired!");
});
3
What are the different types of event handlers provided by JavaScript?
CO1
โ–ผ

Types of Event Handlers in JavaScript

  1. Mouse Event Handlers
    • onclick โ€” single mouse click
    • ondblclick โ€” double click
    • onmouseover โ€” mouse enters element
    • onmouseout โ€” mouse leaves element
    • onmousemove โ€” mouse moves over element
    • onmousedown / onmouseup โ€” mouse button pressed/released
  2. Keyboard Event Handlers
    • onkeydown โ€” key is pressed down
    • onkeyup โ€” key is released
    • onkeypress โ€” key is pressed and character produced (deprecated)
  3. Form Event Handlers
    • onsubmit โ€” form submitted
    • onreset โ€” form reset
    • onchange โ€” value changes and focus lost
    • onfocus โ€” element gains focus
    • onblur โ€” element loses focus
    • oninput โ€” value changes instantly (each keystroke)
  4. Window/Document Event Handlers
    • onload โ€” page/image fully loaded
    • onunload โ€” page is being closed
    • onresize โ€” browser window resized
    • onscroll โ€” page is scrolled
  5. Clipboard Event Handlers: oncopy, oncut, onpaste
  6. Drag Event Handlers: ondrag, ondrop, ondragstart, ondragend
// Examples of different event types
document.onkeydown = function(e) {
    console.log("Key pressed: " + e.key);
};

document.getElementById("myInput").onfocus = function() {
    console.log("Input focused!");
};

window.onload = function() {
    console.log("Page fully loaded");
};
4
Explain regular expression with example.
CO1
โ–ผ

Definition

A Regular Expression (RegEx) is a sequence of characters that forms a search pattern. In JavaScript, RegEx is used to match, search, replace, or validate strings. It is defined using /pattern/flags or new RegExp('pattern').

Common Symbols

SymbolMeaningExample
.Any single character/h.t/ โ†’ "hat", "hot"
*Zero or more occurrences/ab*/ โ†’ "a", "ab", "abb"
+One or more occurrences/ab+/ โ†’ "ab", "abb"
?Zero or one occurrence/colou?r/ โ†’ "color"/"colour"
^Start of string/^Hello/
$End of string/World$/
\dAny digit [0-9]/\d+/ โ†’ "123"
\wWord character [a-zA-Z0-9_]/\w+/
[]Character class/[aeiou]/

Flags

  • i โ€” case insensitive
  • g โ€” global (find all matches)
  • m โ€” multiline
// Creating RegEx
let p1 = /hello/i;                    // literal syntax
let p2 = new RegExp("hello", "i");   // constructor

// test() โ€“ returns true/false
console.log(p1.test("Hello World"));  // true
console.log(p1.test("Hi World"));     // false

// match() โ€“ find matches
let str = "I love JavaScript and Java";
let result = str.match(/Java\w*/g);
console.log(result);  // ["JavaScript", "Java"]

// replace()
let s = "cat bat sat";
console.log(s.replace(/[bcs]at/g, "dog")); // "dog dog dog"

// Email validation example
let emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailReg.test("adii@sppu.edu.in")); // true
5
Explain in detail input/output in JavaScript?
CO1
โ–ผ

Input Methods in JavaScript

  1. prompt() โ€” Shows dialog box; user types input. Returns string.
    let name = prompt("Enter your name:", "Default");
    console.log("Hello, " + name);
  2. HTML Form Inputs โ€” User enters data via input elements.
    // <input type="text" id="uname">
    let name = document.getElementById("uname").value;
  3. confirm() โ€” Returns true (OK) or false (Cancel).
    let ans = confirm("Do you want to continue?");
    if (ans) { alert("Continuing..."); }

Output Methods in JavaScript

  1. document.write() โ€” Writes directly into HTML page.
    document.write("<h2>Hello World</h2>");  // Use with caution
  2. alert() โ€” Popup message box.
    alert("This is an alert message!");
  3. console.log() โ€” Writes to browser developer console.
    console.log("Debug:", 42);
    console.error("Error occurred");
    console.warn("Warning!");
  4. innerHTML / textContent โ€” Updates content of an HTML element.
    document.getElementById("result").innerHTML = "<b>Output Here</b>";
    document.getElementById("result").textContent = "Plain Text Only";
โœ… Preferred: Use innerHTML / textContent for DOM output. Use console.log() for debugging. Avoid document.write() after page load.
6
What is the OnMouseOver Event Handler in JavaScript?
CO1
โ–ผ

Definition

The onmouseover event handler fires when the user moves the mouse pointer onto an HTML element (or any of its children). It is widely used to create hover effects, tooltips, image swapping, and menu highlighting.

Its counterpart onmouseout fires when the mouse leaves the element.

Syntax

<!-- Method 1: HTML Attribute -->
<p onmouseover="this.style.color='red'">Hover me!</p>

// Method 2: JavaScript
let box = document.getElementById("box");

box.onmouseover = function() {
    box.style.backgroundColor = "#7c6ff7";
    box.textContent = "Mouse is OVER!";
};

box.onmouseout = function() {
    box.style.backgroundColor = "";
    box.textContent = "Hover over me";
};

// Method 3: addEventListener
box.addEventListener("mouseover", function() {
    console.log("Mouse entered the element!");
});

Practical Use: Image Swap

<img id="myImg" src="normal.jpg"
     onmouseover="this.src='hover.jpg'"
     onmouseout="this.src='normal.jpg'">
โš ๏ธ onmouseover fires on the element AND its children. Use onmouseenter to avoid child-triggered fires.

Assignment 2 โ€” Data Types and Variables

7 Questions ยท CO2

1
What is the use of isNaN function? Explain with example.
CO2
โ–ผ

Definition

isNaN() stands for "is Not a Number". It is a built-in JavaScript function that checks whether a given value is NaN (Not a Number) or cannot be converted to a number. Returns true if it is NaN, false if it is a valid number.

Syntax

isNaN(value)   // older global function
Number.isNaN(value) // ES6 โ€“ stricter version, doesn't coerce

Examples

console.log(isNaN(123));          // false  โ†’ 123 is a number
console.log(isNaN("hello"));      // true   โ†’ "hello" is not a number
console.log(isNaN("123"));        // false  โ†’ "123" converts to 123
console.log(isNaN(NaN));           // true   โ†’ NaN itself
console.log(isNaN(undefined));   // true   โ†’ undefined โ†’ NaN
console.log(isNaN(null));         // false  โ†’ null converts to 0
console.log(isNaN(true));         // false  โ†’ true converts to 1

// Practical use: validate user input
let age = prompt("Enter your age:");
if (isNaN(age)) {
    alert("Invalid! Please enter a number.");
} else {
    alert("Your age is: " + age);
}
โš ๏ธ isNaN("") returns false (empty string converts to 0). Use Number.isNaN() for strict checks.
2
What is === operator? Explain with example.
CO2
โ–ผ

Definition

The === is the strict equality operator (also called the identity operator). It checks both value AND data type without performing any type conversion (coercion). This is different from == which converts types before comparing.

== vs === Comparison

Expression== Result=== ResultReason
5 == "5"truefalse=== checks type: number โ‰  string
0 == falsetruefalsefalse converts to 0 in ==
null == undefinedtruefalsedifferent types
5 === 5truetruesame value AND same type
"" == falsetruefalsecoercion happens in ==
// == (loose equality โ€“ type coercion occurs)
console.log(5 == "5");       // true  (converts "5" to 5)
console.log(0 == false);    // true  (false converts to 0)

// === (strict equality โ€“ no conversion)
console.log(5 === "5");      // false (number vs string)
console.log(5 === 5);        // true  (same value, same type)
console.log(null === undefined); // false

// Best practice: always use === to avoid bugs
let val = prompt("Enter 5:");  // returns string
console.log(val == 5);   // true  (loose โ€“ risky)
console.log(val === 5);  // false (strict โ€“ correct)
โœ… Always use === (strict equality) in JavaScript to avoid unexpected type coercion bugs.
3
What are all the looping structures in JavaScript? Explain with example.
CO2
โ–ผ

JavaScript Looping Structures

  1. for loop โ€” Used when number of iterations is known.
    for (let i = 0; i < 5; i++) {
        console.log("i = " + i);   // 0 1 2 3 4
    }
  2. while loop โ€” Executes while the condition is true (checks condition FIRST).
    let i = 0;
    while (i < 5) {
        console.log(i);
        i++;
    }
  3. do...while loop โ€” Executes at least ONCE, then checks condition.
    let i = 0;
    do {
        console.log(i);
        i++;
    } while (i < 5);   // runs min once even if false
  4. for...in loop โ€” Iterates over keys of an object.
    let student = { name: "Adii", branch: "ENTC", year: 4 };
    for (let key in student) {
        console.log(key + ": " + student[key]);
    }
    // name: Adii  |  branch: ENTC  |  year: 4
  5. for...of loop (ES6) โ€” Iterates over values of iterable (arrays, strings).
    let marks = [88, 92, 76, 95];
    for (let mark of marks) {
        console.log(mark);   // 88 92 76 95
    }
    
    for (let ch of "ENTC") {
        console.log(ch);     // E N T C
    }
โš ๏ธ Use break to exit a loop early; use continue to skip the current iteration.
4
What is the function of the delete operator? Explain with example.
CO2
โ–ผ

Definition

The delete operator is used to remove a property from an object or an element from an array. It returns true on success. After deletion, the property becomes undefined.

Key Points

  • Cannot delete variables declared with var, let, or const
  • Can delete properties of objects
  • Deleting array element leaves a "hole" (length unchanged)
  • Returns true even if property doesn't exist
// 1. Deleting object property
let student = { name: "Adii", age: 21, city: "Pune" };
console.log(delete student.city);  // true
console.log(student);               // { name: "Adii", age: 21 }

// 2. Deleting array element (leaves undefined hole)
let arr = [10, 20, 30, 40];
delete arr[2];
console.log(arr);         // [10, 20, undefined, 40]
console.log(arr.length);  // 4 (length UNCHANGED!)

// 3. Cannot delete var/let/const
var x = 100;
console.log(delete x);   // false โ€“ cannot delete
console.log(x);           // 100 โ€“ still exists

// 4. Can delete global implicit variable
y = 50;  // no let/var
console.log(delete y);  // true
โœ… To properly remove array elements without leaving holes, use splice() instead of delete.
5
What is an undefined value in JavaScript?
CO2
โ–ผ

Definition

undefined is a primitive data type in JavaScript. A variable has the value undefined when it has been declared but has not yet been assigned a value. It represents "absence of a value".

Situations where undefined occurs

// 1. Declared but not assigned
let x;
console.log(x);              // undefined

// 2. Function returns nothing
function greet() { console.log("Hi"); }
let result = greet();
console.log(result);         // undefined

// 3. Accessing non-existent object property
let obj = { name: "Adii" };
console.log(obj.age);        // undefined

// 4. Missing function parameter
function add(a, b) { return a + b; }
console.log(add(5));          // NaN (b is undefined)

// 5. Accessing out-of-bounds array index
let arr = [1, 2, 3];
console.log(arr[10]);        // undefined

// Type check
console.log(typeof undefined); // "undefined"

undefined vs null

Featureundefinednull
MeaningDeclared but no value assigned (automatic)Intentionally empty (manually set)
Typeundefinedobject (JS bug)
== nulltrue (loose)true
=== nullfalsetrue
6
What are the two basic groups of data types in JavaScript? Explain it.
CO2
โ–ผ

Group 1: Primitive (Value) Data Types

Stored directly in memory (stack). Passed by value โ€” a copy is made on assignment.

TypeExampleDescription
Number42, 3.14, -5All numeric values (int & float)
String"Hello", 'JS'Text enclosed in quotes
Booleantrue, falseLogical true/false
UndefinedundefinedDeclared but not assigned
NullnullIntentional empty value
Symbol (ES6)Symbol('id')Unique identifier
BigInt (ES2020)9007199254nArbitrarily large integers
let num  = 42;
let str  = "Hello SPPU";
let bool = true;
let u;                       // undefined
let n    = null;

// Passed by VALUE (copy)
let a = 10, b = a;
b = 99;
console.log(a); // 10 (unchanged)

Group 2: Reference (Non-Primitive) Data Types

Stored in heap memory; variable holds a reference. Passed by reference โ€” both point to same object.

TypeExampleDescription
Object{name: "Adii"}Key-value collection
Array[1, 2, 3]Ordered list of values
Functionfunction f() {}Callable block of code
let student = { name: "Adii", branch: "ENTC" };
let arr     = [88, 92, 76];

// Passed by REFERENCE
let s2 = student;
s2.name = "Changed";
console.log(student.name); // "Changed" โ€“ same object!
7
What is the use of typeof operator? Explain with example.
CO2
โ–ผ

Definition

The typeof operator is a unary operator that returns a string indicating the data type of its operand. It is used for type checking before performing operations on unknown values.

Syntax

typeof value      // without parentheses (preferred)
typeof(value)     // with parentheses (also valid)

typeof Results

Valuetypeof Result
42"number"
"Hello""string"
true"boolean"
undefined"undefined"
null"object" โ† known JS bug!
{}"object"
[]"object"
function(){}"function"
Symbol()"symbol"
console.log(typeof 42);           // "number"
console.log(typeof "SPPU");       // "string"
console.log(typeof true);          // "boolean"
console.log(typeof undefined);    // "undefined"
console.log(typeof null);          // "object" โ† bug
console.log(typeof {});            // "object"
console.log(typeof []);            // "object"
console.log(typeof function(){}); // "function"

// Practical use: type-safe function
function addSafe(a, b) {
    if (typeof a !== "number" || typeof b !== "number") {
        return "Error: both must be numbers!";
    }
    return a + b;
}
console.log(addSafe(5, 3));       // 8
console.log(addSafe(5, "hi"));    // Error: both must be numbers!

Assignment 3 โ€” Functions and Objects

7 Questions ยท CO3

1
What are the 3 types of functions in JavaScript?
CO3
โ–ผ

Type 1: Named Function (Function Declaration)

Defined using the function keyword with a name. Hoisted โ€” can be called before definition.

function add(a, b) {
    return a + b;
}
console.log(add(3, 4));  // 7

Type 2: Anonymous Function (Function Expression)

A function without a name, assigned to a variable. Not hoisted โ€” must be defined before calling.

let multiply = function(a, b) {
    return a * b;
};
console.log(multiply(3, 4));  // 12

Type 3: Arrow Function (ES6)

Shorter syntax using =>. No own this context. Best for callbacks and short expressions.

let subtract = (a, b) => a - b;
console.log(subtract(10, 4));   // 6

// Multi-line arrow function
let power = (base, exp) => {
    let result = 1;
    for (let i = 0; i < exp; i++) result *= base;
    return result;
};
console.log(power(2, 8));  // 256
๐Ÿ“Œ Additional types: IIFE (Immediately Invoked), Generator Functions, Async Functions
2
What is global variable and local variable in JavaScript?
CO3
โ–ผ
FeatureGlobal VariableLocal Variable
DeclaredOutside any functionInside a function
ScopeEntire script / programOnly within the function
LifetimeEntire script executionDestroyed after function ends
AccessAnywhere in programOnly inside the function
// Global variable
let globalVar = "I am GLOBAL";

function display() {
    // Local variable
    let localVar = "I am LOCAL";

    console.log(globalVar);  // โœ… Accessible
    console.log(localVar);   // โœ… Accessible
}

display();
console.log(globalVar);  // โœ… Accessible
// console.log(localVar);  โŒ ReferenceError: not accessible
3
What happens if global variable and local variables have same name in the class?
CO3
โ–ผ

Variable Shadowing

When a local variable and a global variable share the same name, the local variable shadows (masks) the global inside the function. The global variable remains unchanged outside.

This concept is also called Variable Shadowing or Name Masking.

let name = "Global Adii";   // global variable

function display() {
    let name = "Local Adii";  // local โ€“ shadows global
    console.log("Inside:", name);  // "Local Adii"
}

display();
console.log("Outside:", name);   // "Global Adii" โ€“ unchanged

Accessing global inside function (use window)

var city = "Pune";   // global (var attaches to window)

function test() {
    var city = "Mumbai";  // local shadow
    console.log(city);          // "Mumbai" (local)
    console.log(window.city);   // "Pune" (global via window)
}
test();
4
Which function converts local variables into array?
CO3
โ–ผ

The arguments Object

Inside every regular function (not arrow functions), JavaScript provides an arguments object โ€” an array-like object containing all passed parameters. To convert it to a real array, use Array.from() or the spread operator [...arguments].

function showArgs() {
    console.log(arguments);              // Arguments { 0:10, 1:20, 2:30 }
    let arr = Array.from(arguments);     // convert to Array
    console.log(arr);                    // [10, 20, 30]
    return arr;
}
showArgs(10, 20, 30);

// Alternative: spread operator
function sum() {
    let nums = [...arguments];           // spread to array
    return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4, 5));  // 15

// ES6 Rest Parameters (modern way)
function sumRest(...nums) {           // nums is already an array
    return nums.reduce((a, b) => a + b, 0);
}
console.log(sumRest(1, 2, 3));     // 6
โœ… Modern answer: Use Rest Parameters (...args) which directly gives an array.
5
Which variables are given preference in function โ€“ local or global?
CO3
โ–ผ

Local Variables are Given Preference

When a local and global variable share the same name, local variable is always preferred inside the function. This is governed by JavaScript's Lexical Scoping (also called scope chain resolution).

Scope Chain: JS looks for a variable starting from the innermost scope and moves outward until found.

let x = 100;   // global

function outer() {
    let x = 50;  // local to outer
    
    function inner() {
        let x = 25;  // local to inner โ€“ highest preference here
        console.log("inner x:", x);   // 25
    }
    inner();
    console.log("outer x:", x);     // 50
}

outer();
console.log("global x:", x);      // 100

Scope resolution order: Local โ†’ Enclosing โ†’ Global โ†’ Built-in (LEGB rule).

6
What is masking in JavaScript?
CO3
โ–ผ

Definition

Masking in JavaScript refers to hiding or overriding a variable in an outer scope by declaring another variable with the same name in an inner scope. The inner variable "masks" (hides) the outer one within that scope.

Masking also commonly refers to hiding sensitive data characters (e.g., masking a password or card number with * symbols).

Variable Masking (Scope Masking)

let score = 90;   // global

function test() {
    let score = 55;  // masks global 'score'
    console.log("Inside:", score);  // 55
}

test();
console.log("Outside:", score);   // 90 โ€“ original unchanged

Data Masking (Sensitive Data)

function maskData(str, visible = 4, maskChar = "*") {
    let masked = maskChar.repeat(str.length - visible);
    let shown  = str.slice(-visible);
    return masked + shown;
}
console.log(maskData("9876543210", 4)); // ******3210
console.log(maskData("SecretPass", 1)); // *********s
7
How to replace characters except last with the specified mask character in JavaScript?
CO3
โ–ผ

Method 1: Using slice() + repeat()

function maskExceptLast(str, maskChar = "*", keepLast = 1) {
    if (str.length <= keepLast) return str;
    let maskedPart  = maskChar.repeat(str.length - keepLast);
    let visiblePart = str.slice(-keepLast);
    return maskedPart + visiblePart;
}

console.log(maskExceptLast("Hello"));          // "****o"
console.log(maskExceptLast("9876543210", "X", 4)); // "XXXXXX3210"
console.log(maskExceptLast("MyPassword", "*", 2));  // "********rd"

Method 2: Using Regular Expression

function maskWithRegex(str, maskChar = "*") {
    // .(?=.) โ†’ any char that is followed by another char
    return str.replace(/.(?=.)/g, maskChar);
}
console.log(maskWithRegex("HelloWorld"));  // "*********d"
console.log(maskWithRegex("ENTC", "#"));   // "###C"

Method 3: Using split/map/join

function maskSplit(str, keepLast = 1) {
    return str.split("")
              .map((ch, i) => i < str.length - keepLast ? "*" : ch)
              .join("");
}
console.log(maskSplit("Sinhgad", 3));  // "****gad"

Assignment 4 โ€” Regular Expressions

8 Questions ยท CO4

1
What is use of Regular Expressions?
CO4
โ–ผ

Definition

A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. It is used for pattern matching and text processing in strings.

Uses of Regular Expressions

  1. Pattern Matching โ€” Check if a string contains a pattern.
    /javascript/i.test("I love JavaScript");  // true
  2. Input Validation โ€” Validate email, phone, password format.
    let emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    emailReg.test("user@gmail.com");  // true
  3. Search and Replace โ€” Find text and replace it.
    "Hello World".replace(/World/, "JS"); // "Hello JS"
  4. Extracting Data โ€” Extract dates, phone numbers, etc.
    "Call 9876543210 now".match(/\d{10}/); // ["9876543210"]
  5. Splitting Strings โ€” Split by pattern.
    "one1two2three".split(/\d/);  // ["one","two","three"]
  6. Counting Occurrences โ€” Count words, characters.
  7. URL/HTML Parsing โ€” Extract or validate URLs, tags.
2
What the mean of different symbols like ^ $ in Regular Expression?
CO4
โ–ผ
SymbolMeaningExample
^Start of string (anchor)/^Hello/ โ†’ starts with "Hello"
$End of string (anchor)/World$/ โ†’ ends with "World"
.Any character except newline/h.t/ โ†’ "hat", "hot", "hit"
*0 or more occurrences/ab*/ โ†’ "a", "ab", "abbb"
+1 or more occurrences/ab+/ โ†’ "ab", "abb" (not "a")
?0 or 1 occurrence (optional)/colou?r/ โ†’ "color" or "colour"
{n}Exactly n occurrences/\d{3}/ โ†’ exactly 3 digits
{n,m}Between n and m occurrences/\d{2,4}/
[abc]Character class/[aeiou]/ โ†’ any vowel
[^abc]Negated character class/[^aeiou]/ โ†’ not a vowel
\dAny digit [0-9]/\d+/ โ†’ "123"
\DNon-digit/\D+/ โ†’ "abc"
\wWord char [a-zA-Z0-9_]/\w+/ โ†’ "Hello_123"
\WNon-word character/\W/
\sWhitespace (space, tab, newline)/\s+/
|Alternation (OR)/cat|dog/ โ†’ "cat" or "dog"
()Capturing group/(\d{4})/
let str = "Hello World 123";
console.log(/^Hello/.test(str));  // true  โ€“ starts with "Hello"
console.log(/123$/.test(str));    // true  โ€“ ends with "123"
console.log(/\d+/.test(str));     // true  โ€“ has digits
console.log(/^\d+$/.test(str));   // false โ€“ not all digits
console.log(/^\d+$/.test("12345")); // true
3
What's the difference between greedy and non-greedy matching?
CO4
โ–ผ
FeatureGreedyNon-greedy (Lazy)
DefaultYesNo (add ? to quantifier)
BehaviorMatches as MUCH as possibleMatches as LITTLE as possible
Quantifiers* + ? {n,m}*? +? ?? {n,m}?
let html = "<div>Hello</div><div>World</div>";

// Greedy: .* matches as MUCH as possible โ†’ from first < to LAST >
let greedy = html.match(/<.*>/);
console.log(greedy[0]);
// "<div>Hello</div><div>World</div>" โ† entire string!

// Non-greedy: .*? matches as LITTLE as possible โ†’ first tag only
let lazy = html.match(/<.*?>/);
console.log(lazy[0]);
// "<div>" โ† first tag only

// Get all tags using non-greedy + global flag
let allTags = html.match(/<.*?>/g);
console.log(allTags);
// ["<div>", "</div>", "<div>", "</div>"]
4
What are the string methods available in regular expression in JavaScript?
CO4
โ–ผ

String Methods that use RegEx

  1. test() โ€” RegEx method. Returns true/false.
    /\d+/.test("Age: 21");  // true
  2. exec() โ€” RegEx method. Returns match array with index info.
    /(\d+)/.exec("Age: 21");  // ["21", "21", index:5]
  3. match() โ€” Returns array of matches.
    "cat bat hat".match(/[bch]at/g);  // ["cat","bat","hat"]
  4. matchAll() โ€” Returns iterator of all matches (with capture groups).
    let iter = "test1 test2".matchAll(/test(\d)/g);
    for (let m of iter) console.log(m[0], m[1]);
  5. search() โ€” Returns index of first match (or -1).
    "Hello World".search(/World/);  // 6
  6. replace() โ€” Replace first (or all with /g) match.
    "cat bat cat".replace(/cat/g, "dog"); // "dog bat dog"
  7. replaceAll() โ€” Replace all matches.
    "aaa".replaceAll(/a/g, "b");  // "bbb"
  8. split() โ€” Split string by RegEx pattern.
    "one1two2three".split(/\d/);  // ["one","two","three"]
5
Write a JavaScript program to test the first character of a string is uppercase or not.
CO4
โ–ผ
function isFirstUpperCase(str) {
    if (!str || str.trim() === "") {
        return "String is empty";
    }

    // ^ = start of string, [A-Z] = uppercase letter
    let pattern = /^[A-Z]/;

    if (pattern.test(str)) {
        return `"${str}" โ€“ First char '${str[0]}' is UPPERCASE โœ“`;
    } else {
        return `"${str}" โ€“ First char '${str[0]}' is NOT uppercase โœ—`;
    }
}

// Test Cases
console.log(isFirstUpperCase("Hello"));      // UPPERCASE โœ“
console.log(isFirstUpperCase("hello"));      // NOT uppercase โœ—
console.log(isFirstUpperCase("JavaScript")); // UPPERCASE โœ“
console.log(isFirstUpperCase("123abc"));     // NOT uppercase โœ—
console.log(isFirstUpperCase(""));            // String is empty
6
Write a JavaScript program to search a date within a string.
CO4
โ–ผ
function findDates(str) {
    // Patterns for common date formats
    let patterns = [
        /\b(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})\b/g,  // DD/MM/YYYY
        /\b(\d{4})[\/\-](\d{2})[\/\-](\d{2})\b/g         // YYYY-MM-DD
    ];

    let found = [];
    patterns.forEach(p => {
        let matches = str.match(p);
        if (matches) found = found.concat(matches);
    });

    if (found.length > 0) {
        console.log("โœ… Dates found:", found.join(", "));
    } else {
        console.log("โŒ No date found in string.");
    }
    return found;
}

// Test Cases
findDates("Birthday: 15/08/2002, Exam: 01-06-2025");
// โœ… Dates found: 15/08/2002, 01-06-2025

findDates("Event on 2025-12-25 and also 2026-01-01");
// โœ… Dates found: 2025-12-25, 2026-01-01

findDates("No date here at all");
// โŒ No date found in string.
7
Write a pattern that matches e-mail addresses.
CO4
โ–ผ
// Email validation pattern
let emailPattern = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;

/*
Pattern breakdown:
^                    Start of string
[a-zA-Z0-9._%+\-]+  One or more valid chars before @
@                    Literal @ symbol (required)
[a-zA-Z0-9.\-]+     Domain name (letters, digits, dot, hyphen)
\.                   Literal dot (escaped)
[a-zA-Z]{2,}        TLD โ€“ min 2 letters (com, in, org, edu)
$                    End of string
*/

function validateEmail(email) {
    if (emailPattern.test(email))
        console.log(`โœ… "${email}" is VALID`);
    else
        console.log(`โŒ "${email}" is INVALID`);
}

// Test Cases
validateEmail("adii@example.com");        // โœ… VALID
validateEmail("student@sppu.edu.in");     // โœ… VALID
validateEmail("user.name+tag@domain.co"); // โœ… VALID
validateEmail("invalid@");               // โŒ INVALID
validateEmail("@nodomain.com");           // โŒ INVALID
validateEmail("no_at_sign");             // โŒ INVALID
validateEmail("user@domain.c");           // โŒ INVALID (TLD < 2)
8
Write a JavaScript program to count number of words in string.
CO4
โ–ผ
// Method 1: split on whitespace
function countWords(str) {
    if (!str || str.trim() === "") {
        console.log("Empty string. Word count: 0");
        return 0;
    }
    // \s+ matches one or more whitespace (handles extra spaces)
    let words = str.trim().split(/\s+/);
    console.log(`String: "${str}"`);
    console.log(`Word Count: ${words.length}`);
    console.log(`Words: [${words.join(", ")}]`);
    return words.length;
}

// Method 2: using match() with word boundary
function countWordsRegex(str) {
    // \b\w+\b โ†’ matches whole words
    let matches = str.match(/\b\w+\b/g);
    return matches ? matches.length : 0;
}

// Test Cases
countWords("Hello World");              // 2
countWords("JavaScript is awesome");    // 3
countWords("  Extra   spaces  here  ");  // 3 (extra spaces handled)
countWords("OneWord");                  // 1
countWords("");                         // 0

console.log(countWordsRegex("Count these 5 words here")); // 5

Assignment 5 โ€” Fundamental Client-Side JavaScript & Event Handling

8 Questions ยท CO5

1
What is the Document Object Model used for in JavaScript?
CO5
โ–ผ

Definition

The Document Object Model (DOM) is a programming interface/API that represents an HTML or XML document as a hierarchical tree structure. Every element, attribute, and text in the HTML page becomes a node in this tree, which JavaScript can access and modify dynamically.

Uses of DOM in JavaScript

  1. Accessing Elements โ€” Select HTML elements by ID, class, tag.
    document.getElementById("heading");
    document.querySelector(".myClass");
  2. Modifying Content โ€” Change text or HTML of elements.
    document.getElementById("para").innerHTML = "New Content";
  3. Changing Styles โ€” Modify CSS dynamically.
    document.getElementById("box").style.color = "red";
  4. Adding/Removing Elements โ€” Create or delete HTML nodes.
    let div = document.createElement("div");
    document.body.appendChild(div);
  5. Event Handling โ€” Respond to user interactions.
  6. Form Validation โ€” Read and validate form inputs before submission.
2
What is JavaScript and how JavaScript worked with DOM?
CO5
โ–ผ

JavaScript

JavaScript is a lightweight, interpreted, event-driven scripting language used for client-side web development. It makes static HTML pages dynamic and interactive.

How JS Works with DOM

  1. Browser parses HTML โ†’ builds DOM tree in memory
  2. JS accesses DOM through the built-in document object
  3. JS reads, modifies, adds, or deletes nodes
  4. Changes to DOM automatically update the rendered page
/* DOM Tree for:
   <html>
     <head><title>Page</title></head>
     <body>
       <h1 id="title">Hello</h1>
       <button>Click</button>
     </body>
   </html>

   Document โ†’ html โ†’ head โ†’ title
                   โ†’ body โ†’ h1#title
                           โ†’ button
*/

// JS + DOM interaction
function changeTitle() {
    // 1. Access element
    let h1 = document.getElementById("title");

    // 2. Modify content
    h1.innerHTML = "Changed by JavaScript!";

    // 3. Change style
    h1.style.color = "#7c6ff7";
    h1.style.fontSize = "2rem";
}

// 4. Attach to button
document.querySelector("button")
    .addEventListener("click", changeTitle);
3
What are the levels involved in DOM?
CO5
โ–ผ

DOM Levels (Specifications)

  1. DOM Level 0 (Pre-standard)
    • Basic event handling via inline attributes (onclick, onload)
    • Access via document.forms[], document.images[]
    • Not an official W3C spec โ€” browser-specific
  2. DOM Level 1 (W3C 1998)
    • Core: Access elements โ€” getElementById(), getElementsByTagName()
    • HTML: Navigate and modify the document structure
    • Tree structure became standardized
  3. DOM Level 2 (W3C 2000)
    • Event model: addEventListener(), removeEventListener()
    • CSS/Style manipulation via element.style
    • DOM Traversal & Range: navigate parent/child/sibling nodes
    • Namespace support
  4. DOM Level 3 (W3C 2004)
    • Load & Save, XPath support
    • Keyboard events standardized
    • Methods: document.adoptNode(), document.normalizeDocument()
๐Ÿ“Œ Today, DOM is maintained as a living standard by WHATWG (Web Hypertext Application Technology Working Group) at dom.spec.whatwg.org
4
What is an event and how can you define an event in HTML DOM?
CO5
โ–ผ

What is an Event?

An event is an action or occurrence detected by JavaScript โ€” such as a mouse click, key press, page load, form submission, etc. Events make web pages interactive by allowing JavaScript to respond to these actions.

3 Ways to Define Events in HTML DOM

  1. Inline HTML attribute (oldest way)
    <button onclick="alert('Clicked!')">Click</button>
    <input type="text" onkeyup="showInput(this.value)">
    <body onload="init()">
  2. DOM Event Property
    let btn = document.getElementById("myBtn");
    
    // Only ONE handler per event
    btn.onclick = function() {
        alert("Button clicked!");
    };
    
    // Overwrites previous
    btn.onclick = function() {
        console.log("Second handler โ€“ first one lost!");
    };
  3. addEventListener() โ€” Recommended (DOM Level 2)
    let btn = document.getElementById("myBtn");
    
    // Multiple handlers for same event
    btn.addEventListener("click", function() {
        console.log("Handler 1");
    });
    btn.addEventListener("click", function() {
        console.log("Handler 2 โ€“ both fire!");
    });
    
    // Remove an event listener
    function handler() { console.log("click"); }
    btn.addEventListener("click", handler);
    btn.removeEventListener("click", handler);
5
How HTML DOM allows JavaScript to change the text color and background color of a particular element?
CO5
โ–ผ

Explanation

JavaScript accesses DOM elements and modifies their style property, which maps directly to inline CSS. CSS property names with hyphens are written in camelCase in JavaScript.

// Accessing an element
let elem = document.getElementById("myPara");

// Change text color
elem.style.color = "red";                 // named color
elem.style.color = "#7c6ff7";             // hex code
elem.style.color = "rgb(124, 111, 247)";  // rgb

// Change background color
elem.style.backgroundColor = "yellow";
elem.style.backgroundColor = "#1a1d27";

// CSS property โ†’ JS camelCase mapping
// background-color  โ†’ backgroundColor
// font-size         โ†’ fontSize
// border-radius     โ†’ borderRadius

/* Full Example with Button */
function changeColors() {
    let p = document.getElementById("demo");
    p.style.color            = "white";
    p.style.backgroundColor  = "#4ecdc4";
    p.style.padding          = "10px";
    p.style.borderRadius     = "8px";
}

function resetColors() {
    let p = document.getElementById("demo");
    p.style.color           = "";   // empty = remove inline style
    p.style.backgroundColor = "";
}
โœ… Setting element.style.property = "" removes the inline style and reverts to CSS stylesheet value.
6
What are the HTML DOM methods involved?
CO5
โ–ผ

1. Element Selection Methods

document.getElementById("id")            // single element by ID
document.getElementsByClassName("cls")   // HTMLCollection by class
document.getElementsByTagName("p")       // HTMLCollection by tag
document.querySelector("#id .cls")      // first match (CSS selector)
document.querySelectorAll("p.cls")      // NodeList โ€“ all matches

2. Element Creation & Insertion

document.createElement("div")     // create new element
document.createTextNode("text")   // create text node
elem.appendChild(child)            // add at end
elem.insertBefore(newEl, refEl)   // insert before reference
elem.replaceChild(newEl, oldEl)   // replace child
elem.removeChild(child)           // remove child element
elem.remove()                     // remove itself
elem.cloneNode(true)             // clone with children

3. Attribute Methods

elem.getAttribute("href")          // get attribute value
elem.setAttribute("href", "#")     // set attribute
elem.removeAttribute("disabled")  // remove attribute
elem.hasAttribute("class")        // returns true/false

4. Event Methods

elem.addEventListener("click", fn)    // add listener
elem.removeEventListener("click", fn) // remove listener
elem.dispatchEvent(new Event("click")) // trigger event manually
7
What are the properties of HTML DOM?
CO5
โ–ผ

Content Properties

element.innerHTML     // HTML content (read/write)
element.textContent   // plain text content
element.innerText     // visible text (respects CSS display)
element.value         // value of form elements
element.href          // URL for <a> tags
element.src           // source for <img>, <script>

Style / Class Properties

element.style.color        // inline CSS property
element.className           // full class attribute string
element.classList           // DOMTokenList (add/remove/toggle/contains)
element.id                  // element ID
element.tagName             // tag name ("DIV", "P")
element.nodeType            // 1=element, 3=text, 8=comment

Tree Navigation Properties

element.parentNode          // parent node
element.parentElement       // parent element
element.childNodes          // all child nodes (includes text)
element.children            // child elements only
element.firstChild          // first child node
element.lastChild           // last child node
element.nextSibling         // next sibling node
element.previousSibling     // previous sibling node
element.childElementCount   // number of child elements

Document Properties

document.title              // page title
document.URL                // full URL
document.body               // <body> element
document.head               // <head> element
document.forms              // all form elements
document.images             // all images
document.links              // all <a> with href
8
What is a DOM EventListener method and how it can show the current date and time?
CO5
โ–ผ

EventListener Method

The addEventListener() method attaches an event handler to a DOM element without overwriting existing handlers. Multiple listeners can be added for the same event.

Syntax: element.addEventListener(event, function, useCapture)

/* Full Example: Show current date and time */

<!-- HTML -->
<!--
  <p id="datetime">Click to see date/time</p>
  <button id="showBtn">Show Date & Time</button>
  <button id="liveBtn">Live Clock</button>
-->

let btn = document.getElementById("showBtn");

// One-time click listener
btn.addEventListener("click", function() {
    let now = new Date();

    let date = now.toLocaleDateString("en-IN", {
        day:   "2-digit",
        month: "long",
        year:  "numeric"
    });

    let time = now.toLocaleTimeString("en-IN");

    document.getElementById("datetime").innerHTML =
        `๐Ÿ“… Date: ${date}<br>๐Ÿ• Time: ${time}`;
});

// Live clock โ€“ updates every second
let liveBtn = document.getElementById("liveBtn");
let clockInterval = null;

liveBtn.addEventListener("click", function() {
    if (clockInterval) { clearInterval(clockInterval); clockInterval = null; return; }
    clockInterval = setInterval(function() {
        document.getElementById("datetime").textContent =
            new Date().toLocaleString("en-IN");
    }, 1000);
});
โš ๏ธ useCapture (3rd param) defaults to false (bubble phase). Set to true for capture phase.

Assignment 6 โ€” Using JavaScript (Frames, Window, Forms)

11 Questions ยท CO6

1
What is a frame in JavaScript?
CO6
โ–ผ

Definition

A frame in JavaScript refers to a section of the browser window that displays a separate HTML document. Historically, frames were created using <frameset> and <frame> tags (deprecated in HTML5). Today, <iframe> (inline frame) is the modern equivalent.

The window.frames property provides access to all frames (iframes) within the current window.

<!-- Modern: iframe element -->
<iframe id="myFrame" src="page.html" width="600" height="400"></iframe>

// Accessing frames in JavaScript
console.log(window.frames.length);      // number of iframes

// Access first iframe's window
let frameWin = window.frames[0];

// Access by id via contentWindow
let frame = document.getElementById("myFrame");
let frameDoc = frame.contentDocument;   // DOM of iframe content
let frameWin2 = frame.contentWindow;    // window object of iframe

// Call function inside iframe
frame.contentWindow.someFunction();

// Access parent from inside iframe
// window.parent โ†’ parent window
// window.top โ†’ topmost window
2
What is the window JavaScript?
CO6
โ–ผ

Definition

The window object is the global object in browser-based JavaScript and the top-level object of the Browser Object Model (BOM). It represents the browser window. All global variables and functions automatically become properties of the window object.

Key window Properties & Methods

// Properties
window.innerWidth;        // browser viewport width
window.innerHeight;       // browser viewport height
window.location.href;     // current URL
window.location.hostname; // domain name
window.navigator.userAgent; // browser info
window.history.length;    // # of pages in history
window.screen.width;      // full screen width
window.document;          // the HTML DOM

// Dialog Methods (window. can be omitted)
window.alert("Message!");              // alert box
let ok = window.confirm("Sure?");       // true/false
let val = window.prompt("Enter:", "");  // user input

// Timer Methods
let t1 = window.setTimeout(function() {
    console.log("After 2s");
}, 2000);

let t2 = window.setInterval(function() {
    console.log("Every 1s");
}, 1000);

window.clearTimeout(t1);   // stop setTimeout
window.clearInterval(t2);  // stop setInterval

// Navigation Methods
window.open("https://sppu.ac.in", "_blank"); // open tab
window.close();                                 // close window
window.scrollTo(0, 0);                        // scroll to top
window.history.back();                          // go back
window.location.reload();                       // reload page
3
What is difference between window and document in JavaScript?
CO6
โ–ผ
Featurewindowdocument
Belongs toBrowser Object Model (BOM)Document Object Model (DOM)
RepresentsBrowser window/tabHTML page loaded in window
Top-levelYes โ€“ global objectNo โ€“ property of window
AccessDirectly (global)window.document or just document
Key Propertieslocation, history, navigator, screenbody, head, title, forms, images
Key Methodsalert(), open(), setTimeout()getElementById(), createElement()
Eventsonresize, onscroll, onloadonclick, onkeypress (via elements)
// window โ€“ browser level
console.log(window.innerWidth);       // 1920 (screen width)
console.log(window.location.href);    // "https://..."
window.setInterval(() => {}, 1000);

// document โ€“ page level
console.log(document.title);          // "My Page"
document.getElementById("box").style.color = "red";

// Relationship
console.log(window.document === document); // true!
4
Is window object part of JavaScript?
CO6
โ–ผ

Answer: No โ€” window is NOT part of core JavaScript

The window object is provided by the browser (host environment), not by the JavaScript language (ECMAScript) itself. It is part of the Browser Object Model (BOM).

  • In Browsers โ€” window is the global object; all globals attach to it.
  • In Node.js โ€” There is NO window object; the global object is global.
  • In Web Workers โ€” The global is self, not window.
// In browser: globals become window properties
var x = 42;
console.log(window.x); // 42

function greet() { return "Hi!"; }
console.log(window.greet()); // "Hi!"

// window. prefix is optional in browsers
alert("same as window.alert()");
document.write("same as window.document.write()");

// Detect environment
if (typeof window !== "undefined") {
    console.log("Running in BROWSER");
} else {
    console.log("Running in NODE.JS or other env");
}
5
Which JavaScript event is useful for form validation?
CO6
โ–ผ

Most Useful Events for Form Validation

EventWhen it firesUse case
onsubmitWhen form is submittedFinal validation before sending โญ Most important
oninputEvery keystroke (real-time)Live validation as user types
onblurField loses focusValidate field on tab-out
onchangeValue changes + focus lostValidate after input complete
onfocusField gains focusShow hints/placeholders
// onsubmit โ€“ main validation event
function validateForm() {
    let name = document.getElementById("name").value;
    if (name.trim() === "") {
        alert("Name is required!");
        return false;   // PREVENTS form submission
    }
    return true;       // ALLOWS form submission
}
// <form onsubmit="return validateForm()">

// oninput โ€“ real-time email validation
document.getElementById("email").addEventListener("input", function() {
    let valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.value);
    this.style.borderColor = valid ? "green" : "red";
});
6
How many types of validation are there in JavaScript?
CO6
โ–ผ

3 Main Types of Validation

  1. Client-Side Validation (Browser/JavaScript)
    • Runs in the browser before data is sent to server
    • Fast, immediate user feedback
    • Can be disabled/bypassed (not 100% secure)
  2. Server-Side Validation (Backend)
    • Runs on the web server after form submission
    • More secure โ€” cannot be bypassed by user
    • Slower (requires network round-trip)
    • Always needed as final security layer
  3. HTML5 Built-in Validation
    • Uses HTML5 attributes, handled by browser natively
    • No JavaScript required
    <input type="email" required minlength="5" maxlength="50">
    <input type="number" min="1" max="100">
    <input type="text" pattern="[A-Za-z]{3,}">

Sub-Types within Client-Side Validation

  • Required Field Validation
  • Data Type Validation (isNaN, typeof)
  • Format Validation (RegEx for email, phone)
  • Range Validation (min/max values)
  • Comparison Validation (password match)
  • Length Validation (min/max length)
7
How is form handling done in JavaScript?
CO6
โ–ผ

Steps in Form Handling

  1. Collect data from form fields
  2. Validate the collected data
  3. Process / display / submit the data
<!-- HTML -->
<!--
<form id="myForm" onsubmit="return handleForm()">
  <input type="text" id="name" placeholder="Your name">
  <input type="email" id="email" placeholder="Your email">
  <input type="number" id="age" placeholder="Your age">
  <button type="submit">Submit</button>
  <button type="reset">Reset</button>
</form>
<div id="output"></div>
-->

function handleForm() {
    // Step 1: Collect data
    let name  = document.getElementById("name").value.trim();
    let email = document.getElementById("email").value.trim();
    let age   = parseInt(document.getElementById("age").value);

    // Step 2: Validate
    if (name === "") { alert("Name required!"); return false; }

    let emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailReg.test(email)) { alert("Invalid email!"); return false; }

    if (isNaN(age) || age < 18 || age > 100) {
        alert("Age must be 18โ€“100!"); return false;
    }

    // Step 3: Process โ€“ display output
    document.getElementById("output").innerHTML = `
        <h3>โœ… Form Submitted!</h3>
        <p>Name:  ${name}</p>
        <p>Email: ${email}</p>
        <p>Age:   ${age}</p>`;

    return false; // prevent actual browser submit for demo
}
8
What is Onsubmit in JavaScript?
CO6
โ–ผ

Definition

onsubmit is a JavaScript event that fires when the user submits an HTML form โ€” either by clicking the submit button or pressing Enter in a text field. It is the primary event used for form validation before data is sent to the server.

Key Rules

  • Return false โ†’ Prevents form submission (validation failed)
  • Return true or nothing โ†’ Allows form submission
  • event.preventDefault() also prevents submission (with addEventListener)
// Method 1: Inline onsubmit
// <form onsubmit="return validateForm()">

// Method 2: addEventListener (preferred)
document.getElementById("myForm")
    .addEventListener("submit", function(event) {

        event.preventDefault();  // stop browser submission

        let name = document.getElementById("name").value;

        if (name.trim() === "") {
            alert("Name is required!");
            return;  // stop here
        }

        // Validation passed โ€“ submit programmatically
        console.log("Form is valid! Submitting...");
        // this.submit();
    });
9
What are the different types of form validation?
CO6
โ–ผ
  1. Required Field Validation โ€” Fields cannot be empty.
    if (document.getElementById("name").value === "")
        { alert("Name required!"); return false; }
  2. Data Type Validation โ€” Value is correct type.
    if (isNaN(document.getElementById("age").value))
        { alert("Age must be a number!"); return false; }
  3. Format Validation โ€” RegEx checks (email, phone, date).
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
        { alert("Invalid email!"); return false; }
  4. Range Validation โ€” Value within min/max.
    if (age < 18 || age > 100)
        { alert("Age: 18โ€“100"); return false; }
  5. Comparison Validation โ€” Two fields must match.
    if (pass !== confirmPass)
        { alert("Passwords don't match!"); return false; }
  6. Length Validation โ€” Min/max character length.
    if (name.length < 3 || name.length > 50)
        { alert("Name: 3-50 chars"); return false; }
10
What are the three types of form validation?
CO6
โ–ผ

The 3 Primary Types

  1. Client-Side Validation
    • Done in browser using JavaScript before form is submitted
    • Fast, instant feedback to user; no server round-trip needed
    • Can be bypassed โ€” NOT sufficient alone for security
    function validate() {
        if (field.value === "") { alert("Required"); return false; }
        return true;
    }
  2. Server-Side Validation
    • Done on the web server after form data is received
    • Cannot be bypassed โ€” most secure method
    • Requires network round-trip (slower)
    • Always necessary alongside client-side validation
  3. HTML5 Native/Built-in Validation
    • Uses HTML attributes โ€” browser handles validation automatically
    • No JavaScript code required
    • Limited customization of error messages
    <input type="email" required>
    <input type="number" min="18" max="100">
    <input type="text" pattern="[A-Za-z]{3,}" required>
    <input type="password" minlength="8">
โœ… Best Practice: Use all 3 together โ€” HTML5 for basic, JS for advanced, server-side for security.
11
How do I validate a form before submitting?
CO6
โ–ผ

Complete Form Validation Example

/* HTML Structure:
<form id="regForm" onsubmit="return validateAll()">
  <input type="text"     id="fname"  placeholder="Full Name">
  <span id="nameErr"></span>
  <input type="email"    id="email"  placeholder="Email">
  <span id="emailErr"></span>
  <input type="password" id="pass"   placeholder="Password">
  <input type="password" id="cpass"  placeholder="Confirm">
  <span id="passErr"></span>
  <input type="number"   id="age"    placeholder="Age">
  <span id="ageErr"></span>
  <button type="submit">Register</button>
</form>
*/

function setError(id, msg) {
    document.getElementById(id).textContent = msg;
    document.getElementById(id).style.color = "red";
}
function clearError(id) {
    document.getElementById(id).textContent = "";
}

function validateAll() {
    let isValid = true;

    // 1. Name validation
    let name = document.getElementById("fname").value.trim();
    if (name.length < 3) {
        setError("nameErr", "Name must be at least 3 characters");
        isValid = false;
    } else clearError("nameErr");

    // 2. Email validation
    let email = document.getElementById("email").value;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        setError("emailErr", "Enter a valid email address");
        isValid = false;
    } else clearError("emailErr");

    // 3. Password match validation
    let pass  = document.getElementById("pass").value;
    let cpass = document.getElementById("cpass").value;
    if (pass === "" || pass.length < 6) {
        setError("passErr", "Password must be at least 6 characters");
        isValid = false;
    } else if (pass !== cpass) {
        setError("passErr", "Passwords do not match!");
        isValid = false;
    } else clearError("passErr");

    // 4. Age range validation
    let age = parseInt(document.getElementById("age").value);
    if (isNaN(age) || age < 18 || age > 100) {
        setError("ageErr", "Age must be between 18 and 100");
        isValid = false;
    } else clearError("ageErr");

    // Only submit if ALL validations passed
    if (isValid) {
        alert("โœ… Registration Successful!");
    }
    return isValid;  // false = stop submission, true = allow
}