CACS205 Web Technology

Web TechnologyUnit 410 min read

Client-Side Scripting, Form Handling & Validation (HTML5/JavaScript)

Unit 4 of Web Technology covers client-side scripting (JavaScript), HTML5 form elements, validation techniques (client/server-side), and data handling without relying on server-side databases. Learn how to create interactive forms, validate user input, and manage sessions/cookies—key skills for building dynamic web app


Core Concepts: Client-Side Scripting & Form Handling

1. What is Client-Side Scripting?

Client-side scripting executes on the user’s browser (not the server) using languages like JavaScript. It enables:

  • Dynamic content updates (e.g., auto-filling forms, live search).
  • Validation before submission (e.g., checking email format).
  • Reduced server load (no need to send invalid data to the server).

Why use it?

  • Faster responses (no round-trip to server).
  • Better user experience (immediate feedback).
  • Works offline (with localStorage).

2. HTML5 Forms: New Elements & Attributes

HTML5 introduced semantic form elements for better accessibility and validation. Compare old vs. new:

08162431type8 bitsname8 bitsrequired8 bitspattern8 bits
HTML5 `input` element attributes for email validation (32-bit logical representation)
Old (HTML4) New (HTML5) Purpose
<input type="text"> <input type="email"> Validates email format automatically.
<input type="text"> <input type="url"> Checks for valid URL format.
<input type="text"> <input type="tel"> Optimized for phone numbers.
<input type="text"> <input type="date"> Opens a calendar picker.
<input type="text"> <input type="color"> Color picker dialog.
<textarea> <input type="search"> Adds a "clear" (×) button.
<select> <datalist> Autocomplete suggestions.

Example: Email Validation

<input type="email" name="user_email" placeholder="example@domain.com"
       required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
  • required: Field cannot be empty.
  • pattern: Regex for strict validation.

3. Form Validation: Client-Side vs. Server-Side

Client-Side Server-Side
Runs in browser (JavaScript). Runs on server (PHP, Python).
Faster feedback. More secure (hides logic).
Can be bypassed (e.g., disabled JS). Always executes.
Uses onsubmit event. Uses backend checks (e.g., SQL queries).
sequenceDiagram
    participant User
    participant Browser
    participant Server
    User->>Browser: Enters email: test@example
    Browser->>Browser: Validates (HTML5 + JS)
    Browser-->>User: Shows ✓/✗ immediately
    Browser->>Server: Sends data only if valid
    Server->>Server: Processes (e.g., saves to DB)
    Server-->>User: Confirms via API
Client-side validation workflow (eSewa login example)

Worked Example: eSewa Login Form When you log in to eSewa, the browser first checks:

  1. Is the email valid? (HTML5 type="email").
  2. Is the password ≥8 chars? (JavaScript length check).
  3. Are fields filled? (required attribute). Only if all pass does it send data to the server.

In the Real World

  1. Khalti Payment Forms

    • Uses client-side validation to check card numbers (Luhn algorithm) before submitting.
    • HTML5 type="number" ensures only digits are entered for amounts.
  2. Daraz Product Search

    • datalist provides autocomplete suggestions as you type (e.g., "iPhone 13" auto-completes to "iPhone 13 Pro Max").
    • JavaScript event listeners (oninput) fetch suggestions dynamically.
  3. NTC Electricity Bill Portal

    • Server-side sessions track logged-in users (e.g., session['user_id']) to display personalized bills.
    • Cookies store preferences (e.g., "Remember me" for auto-login).

4. Handling Forms with JavaScript

A. Accessing Form Data

Use document.getElementById() or form.elements:

const form = document.getElementById("myForm");
form.onsubmit = function(event) {
    event.preventDefault(); // Stop form submission
    const name = form.elements["user_name"].value;
    const email = form.elements.email.value;
    console.log(`Name: ${name}, Email: ${email}`);
};

B. Validation Functions

function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

function validatePhone(phone) {
    return /^\d{10}$/.test(phone); // 10-digit Nepalese number
}

Example: Pathao Driver Signup When a driver signs up, JavaScript checks:

  1. License number (must be 10 digits).
  2. Vehicle type (dropdown required).
  3. Profile picture (file size <2MB via onchange event).

5. Sessions vs. Cookies

Feature Cookies Sessions
Storage Stored on client (browser). Stored on server (e.g., PHP session).
Security Vulnerable to XSS attacks. More secure (server-side).
Persistence Can be set to expire (e.g., 7 days). Dies when browser closes (unless configured).
Use Case Tracking preferences (e.g., "Dark Mode"). User login state (e.g., Ncell MyAccount).

Example: Ncell MyAccount Login

  1. User enters credentials → server creates a session (session['user_id'] = 12345).
  2. Session ID is stored in a cookie (PHPSESSID=abc123).
  3. On page refresh, the cookie sends the session ID back to the server.

6. Storing Data Without a Database

Cookies<2KBSession Storage<5MBLocalStorage<10MBIndexedDBNo size limit
Client-side storage hierarchy (Nepali bank login persistence)

A. Cookies

// Set cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

// Read cookie
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    return parts.pop().split(';').shift();
}

B. LocalStorage (Persistent)

// Save
localStorage.setItem("user_prefs", JSON.stringify({ theme: "dark" }));

// Retrieve
const prefs = JSON.parse(localStorage.getItem("user_prefs"));

Example: eSewa "Remember Me"

  • Checks a checkbox → sets a cookie with remember_me=true.
  • On return, the cookie auto-fills the email field.

7. Worked Example: Daraz Order Form

Task: Create a form to submit an order with validation.

<form id="orderForm" onsubmit="return validateOrder()">
    <input type="text" name="product" required placeholder="Product Name">
    <input type="number" name="quantity" min="1" required>
    <input type="email" name="email" required>
    <button type="submit">Place Order</button>
</form>

<script>
function validateOrder() {
    const quantity = parseInt(document.querySelector('[name="quantity"]').value);
    if (quantity <= 0) {
        alert("Quantity must be > 0!");
        return false;
    }
    alert("Order placed! (Server-side processing would happen here.)");
    return true;
}
</script>

Server-Side Equivalent (PHP):

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $product = $_POST["product"];
    $quantity = $_POST["quantity"];
    $email = $_POST["email"];

    // Server-side validation (e.g., check stock in database)
    if ($quantity > 0) {
        echo "Order confirmed! Email: $email";
    } else {
        echo "Invalid quantity!";
    }
}
?>

8. Common Exam Pitfalls

  1. Forgetting event.preventDefault()
    • Without it, the form submits immediately, bypassing JavaScript validation.
  2. Mixing Client/Server Validation
    • Always validate on the server too (client-side can be disabled).
  3. Incorrect Cookie Syntax
    • Must include expires, path, and domain for security.
  4. Not Escaping User Input
    • Use htmlspecialchars() in PHP to prevent XSS attacks.

Exam Tip

  • For script-based questions, always show:
    1. HTML form structure.
    2. JavaScript validation logic.
    3. Server-side handling (even if not required, it’s good practice).
  • For session/cookie questions, compare them in a table and give a real-world example (e.g., "How does Daraz track your cart?").
  • For validation, test edge cases:
    • Empty fields.
    • Invalid formats (e.g., user@.com).
    • Special characters.

sequenceDiagram
    participant User
    participant Browser
    participant Server
    User->>Browser: Enters email in eSewa form
    Browser->>Browser: HTML5 validates format (type="email")
    Browser->>Browser: JavaScript checks length (>6 chars)
    Browser->>Server: Sends data only if valid
    Server->>Server: Creates session (session['user_id'])
    Server->>Browser: Returns success page
    Browser->>User: Displays "Login Successful"

classDiagram
    class FormElement {
        +type: String
        +name: String
        +value: String
        +validate(): Boolean
    }
    class HTML5Form {
        +elements: FormElement[]
        +onsubmit(): void
        +validateAll(): Boolean
    }
    class Server {
        +processForm(data): Response
        +createSession(user): SessionID
    }
    FormElement --> HTML5Form : contained in
    HTML5Form --> Server : submits to
    Server --> HTML5Form : returns response

In the real world

  • Pathao Driver App: Uses client-side validation (JavaScript) to check license numbers (10 digits) and vehicle types (dropdown required) before submitting to the server. Prevents invalid submissions and reduces server load.
  • Ncell MyAccount: Stores login sessions on the server but uses cookies (PHPSESSID) to maintain user state across pages. The cookie expires after inactivity (security measure).
  • eSewa Payment Forms: Implements HTML5 type="tel" for phone validation and localStorage to save payment preferences (e.g., default card) for returning users.

Based on the TU BCA syllabus for Web Technology (CACS205), unit 4.

Discussion

Loading…