IT219 Web Programming II

Web Programming IIUnit 213 min read

HTML Forms & Input Validation: Structure, Validation & Security

Unit 2 of Web Programming II: Covers HTML form elements, validation techniques (client-side and server-side), security best practices, and real-world applications in e-commerce, user authentication, and data collection.

TAKEAWAYS:

  • HTML forms enable user input via text fields, radio buttons, checkboxes, and dropdowns, structured with <form>, <input>, and <label> tags.
  • Client-side validation (JavaScript/CSS) improves UX by catching errors before submission, while server-side validation ensures data integrity.
  • Validation rules include required, pattern, min/max, and custom JavaScript checks for age, email, and password strength.
  • Security risks like XSS and CSRF are mitigated using type="email", type="password", and novalidate attributes where needed.
  • Real-world examples include eSewa’s transaction forms (client-side validation) and Daraz’s checkout (server-side validation for payment data).
  • Default values (value="...") and placeholder text enhance usability by guiding users without mandatory fields.

1. Introduction to HTML Forms

HTML forms are the backbone of interactive web applications, allowing users to submit data to a server. They consist of:

  • A <form> container with action (where data is sent) and method (GET/POST).
  • Input fields (<input>, <textarea>, <select>) with attributes like type, name, placeholder, and required.
  • Labels (<label>) for accessibility and usability.

Key Attributes

Attribute Purpose
action URL where form data is sent (e.g., action="process.php").
method GET (appends data to URL) or POST (sends data hidden).
name Identifies the field in submitted data (e.g., name="username").
type Defines input type (text, email, password, radio, checkbox, etc.).
required Marks a field as mandatory.
placeholder Hint text (e.g., placeholder="Enter name").
value Default value (e.g., value="Mr" for radio buttons).

Example: Basic Form with Validation

<form action="submit.php" method="post">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required placeholder="Enter your name">

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

  <label for="age">Age:</label>
  <input type="number" id="age" name="age" min="1" max="100" required>

  <input type="submit" value="Submit">
</form>

Visual: Form Structure

graph TD
  A["<form>"] --> B["<input type='text' name='name' label='Name'>"]
  B --> C["<input type='email' name='email' label='Email'>"]
  B --> D["<input type='number' name='age' label='Age'>"]
  A --> E["<input type='submit' value='Submit'>"]
  A --> F["<label> tags for accessibility"]

2. Input Field Types

HTML5 introduced specialized input types for better validation and UX.

Common Input Types

Type Example Use Case Validation Example
text Username, name required
email Email addresses pattern="[^@]+@[^@]+\.[^@]+"
password Password fields minlength="8"
number Age, quantity min="1" max="100"
date Birth date min="1900-01-01"
radio Gender (Male/Female) name="gender" value="Male"
checkbox Hobbies (swimming, reading) name="hobby" value="swimming"
select Dropdown menus (countries) required
file Upload images/resumes accept="image/*"

Example: Radio Buttons for Gender

<label>Gender:</label>
<input type="radio" name="gender" value="male" required> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other

Visual: Radio Button States

graph TD
  A["<input type='radio' name='gender' value='male'> Male"]
  A -->|"Selected"| B["<input type='radio' name='gender' value='female' checked> Female"]
  B -->|"Selected"| C["<input type='radio' name='gender' value='other'> Other"]
  A -->|"Unselected"| D["<input type='radio' name='gender' value='male'> Male"]

3. Form Validation

Validation ensures data meets requirements before submission.

DataResponseClient-SideServer-Side
Flow of validation between client and server.

Client-Side Validation (HTML5 + JavaScript)

  • HTML5 Attributes:

    • required: Field cannot be empty.
    • pattern: Regex for custom validation (e.g., phone numbers).
    • min/max: Numeric ranges.
    • step: Increment for numbers (e.g., step="0.5" for decimals).
  • JavaScript Example:

    document.getElementById("submitBtn").addEventListener("click", function() {
      const age = document.getElementById("age").value;
      if (age < 18) {
        alert("You must be at least 18 years old.");
        return false;
      }
    });
    

Server-Side Validation (PHP)

Always validate on the server, even if client-side validation is used.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $age = $_POST["age"];
  if (!is_numeric($age) || $age < 1 || $age > 100) {
    die("Invalid age.");
  }
}
?>

Comparison Table: Client vs. Server Validation

Feature Client-Side Validation Server-Side Validation
Execution Browser (JavaScript/CSS) Server (PHP/Python)
Performance Fast (no server round-trip) Slower (requires HTTP request)
Security Not secure (can be bypassed) Secure (data validated on server)
User Experience Immediate feedback Feedback after submission
Example Tools required, pattern, JS PHP filter_var(), regex

4. Default Values and Placeholders

  • Default Values (value): Pre-fill fields (e.g., radio buttons, dropdowns).
    <input type="text" name="country" value="Nepal">
    
  • Placeholders (placeholder): Hint text that disappears when the user types.
    <input type="email" placeholder="example@email.com">
    

Visual: Default Value vs. Placeholder

<input type='text' value='Nepal'>0<input type='text' placeholder='Nepal'>1
Left: Pre-filled value (persists after submission). Right: Placeholder (disappears on focus).

5. Security Considerations

Forms are vulnerable to attacks like XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgery).

Mitigation Strategies

Risk Solution
XSS Use type="email"/type="password" to sanitize input.
CSRF Add hidden tokens (<input type="hidden" name="csrf_token" value="...">).
SQL Injection Use prepared statements (PHP: PDO).
Data Leakage Avoid GET for sensitive data (use POST).

Example: Secure Form with CSRF Token

<form action="process.php" method="post">
  <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
  <!-- Other fields -->
</form>

6. Real-World Applications

FormInput FieldsValidation RulesSecurity ChecksResponse
Hierarchical breakdown of a secure form submission process.

## In the real world

  1. eSewa Checkout Form:

    • Uses type="email" for user emails and type="password" for OTPs.
    • Validates amount with type="number" and min="1".
    • Client-side validation prevents invalid submissions (e.g., negative amounts).
  2. Daraz Order Form:

    • Dropdowns (<select>) for shipping options with required.
    • JavaScript checks for valid phone numbers (pattern="[0-9]{10}").
    • Server-side validation ensures payment details are correct before processing.
  3. Pathao Ride Request:

    • Radio buttons for pickup/drop locations.
    • Date picker (<input type="date">) for ride scheduling.
    • Default values (e.g., value="Kathmandu" for location) reduce user effort.

Worked Example: Daraz Order Queue Validation Assume Daraz’s checkout form has:

  • Product ID: Numeric, min="1", max="1000".
  • Quantity: min="1", max="10".
  • Email: type="email".

Client-Side Check (JavaScript):

function validateOrder() {
  const productId = document.getElementById("productId").value;
  const quantity = document.getElementById("quantity").value;
  const email = document.getElementById("email").value;

  if (!/^\d+$/.test(productId) || productId < 1 || productId > 1000) {
    alert("Invalid product ID.");
    return false;
  }
  if (quantity < 1 || quantity > 10) {
    alert("Quantity must be between 1 and 10.");
    return false;
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    alert("Invalid email.");
    return false;
  }
  return true;
}

Server-Side Check (PHP):

$productId = $_POST["productId"];
$quantity = $_POST["quantity"];
$email = $_POST["email"];

if (!is_numeric($productId) || $productId < 1 || $productId > 1000) {
  die("Invalid product ID.");
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  die("Invalid email.");
}

7. Common Exam Questions and Solutions

Q1: Why is client-side validation required? Explain with an example.

Answer: Client-side validation improves user experience by providing immediate feedback (e.g., highlighting invalid fields) and reduces server load by preventing invalid submissions. For example:

  • In a Pathao ride request form, JavaScript checks if the pickup location is selected before allowing submission. If not, it shows an error like "Please select a pickup location." This avoids sending incomplete data to the server.

Q2: Explain default values in a form with an example.

Answer: Default values (value="...") pre-fill form fields, reducing user effort. Example:

<form>
  <label>Preferred Payment Method:</label>
  <input type="radio" name="payment" value="credit" checked> Credit Card
  <input type="radio" name="payment" value="debit"> Debit Card
  <input type="radio" name="payment" value="upi"> UPI
</form>

Here, the Credit Card radio button is pre-selected (checked), guiding users toward the most common payment method.

Q3: Validate a form with the following fields:

  • Age: Text field (integer, range 1–100).
  • Gender: Radio buttons (Male/Female/Other).
  • Hobbies: Checkboxes (swimming, reading, coding).

Solution:

<form action="validate.php" method="post">
  <label>Age:</label>
  <input type="number" name="age" min="1" max="100" required>

  <label>Gender:</label>
  <input type="radio" name="gender" value="male" required> Male
  <input type="radio" name="gender" value="female"> Female
  <input type="radio" name="gender" value="other"> Other

  <label>Hobbies:</label>
  <input type="checkbox" name="hobby" value="swimming"> Swimming
  <input type="checkbox" name="hobby" value="reading"> Reading
  <input type="checkbox" name="hobby" value="coding"> Coding

  <input type="submit" value="Submit">
</form>

Server-Side Validation (PHP):

$age = $_POST["age"];
$gender = $_POST["gender"];
$hobbies = $_POST["hobby"] ?? [];

if (!is_numeric($age) || $age < 1 || $age > 100) {
  die("Invalid age.");
}
if (!in_array($gender, ["male", "female", "other"])) {
  die("Invalid gender.");
}

8. Exam Tips

  1. Understand the Difference:

    • Client-side validation = UX improvement (JavaScript/CSS).
    • Server-side validation = security (PHP/Python).
  2. Always Validate on the Server:

    • Assume users can bypass client-side checks (e.g., disabled JavaScript).
  3. Use HTML5 Attributes First:

    • Start with required, type="email", etc., before writing custom JavaScript.
  4. Security is Non-Negotiable:

    • Mention CSRF tokens, input sanitization, and prepared statements in answers.
  5. Practice Coding:

    • Write a full form with validation (client + server) for past exam questions.
  6. Visualize Your Answer:

    • Draw the form structure, show state transitions (e.g., radio button selection), and trace validation logic in tables.

Example Trace Table for Age Validation

Step Action Client-Side Check (JS) Server-Side Check (PHP)
1 User submits form with age=150 Shows error: "Age must be ≤100" Rejected (dies with error)
2 User submits age=25 Passes (1 ≤ 25 ≤ 100) Passes (validates as integer)

Final Note: Forms are the gateway to user interaction. Master validation, security, and UX—these are the pillars of modern web applications. Always test your forms with edge cases (e.g., empty fields, invalid emails). Good luck!

Based on the TU BITM syllabus for Web Programming II (IT219), unit 2.

Discussion

Loading…