IT237 Web Technology I

Web Technology IUnit 612 min read

Form Handling & Client-Side Validation: Techniques, Validation Rules & Security

Unit 6 of Web Technology I covers form handling in HTML/JavaScript, client-side validation techniques (regex, APIs, events), security best practices, and comparison with server-side validation—essential for building secure, user-friendly web applications like eSewa’s payment forms or Daraz’s checkout.

TAKEAWAYS:

  • Client-side validation improves user experience by catching errors instantly (e.g., Daraz’s real-time address format checks) and reduces server load.
  • HTML5 validation attributes (required, pattern, type="email") provide basic validation without JavaScript.
  • JavaScript validation uses regex (e.g., /^[0-9]{10}$/ for phone numbers) and event listeners (onblur, onsubmit) for dynamic checks.
  • Security risks of client-side validation alone include bypassing via disabled JS or browser tools (e.g., modifying a Kathmandu traffic route form’s hidden fields).
  • Form handling involves GET/POST methods, action attributes, and name/id pairs for data submission.
  • Best practices combine client-side validation with server-side checks (e.g., Ncell’s SIM registration forms) and use libraries like Formik or React Hook Form for complex apps.

1. Form Handling in HTML

Forms are the bridge between users and web applications, collecting data via inputs (text, buttons, checkboxes) and submitting it to a server. The core HTML elements include:

08162431action16 bitsmethod4 bitsname12 bitsid16 bitstype8 bitsrequired4 bits
HTML form field attributes in a Daraz order submission (simplified)

Key HTML Form Elements

<form action="/submit" method="POST">
  <label for="name">Name:</label>
  <input type="text" id="name" name="username" required>

  <input type="submit" value="Sign Up">
</form>
  • action: URL where form data is sent (e.g., /submit or https://esewa.com/payment).
  • method: GET (appends data to URL) or POST (sends data in request body).
  • name attribute: Identifies the field in the submitted data (e.g., username=John).
  • required: Basic client-side validation to ensure a field isn’t empty.

Real-World Example: eSewa Payment Form

  • How it uses form handling:
    • action="/process-payment" sends data to eSewa’s server.
    • method="POST" hides sensitive data (like card numbers) from the URL.
    • type="number" ensures the amount field only accepts digits.

Worked Example: Daraz Order Form

Trace how a Daraz order form submits data:

  1. User fills in product ID, quantity, and address.
  2. Clicking "Place Order" triggers onsubmit JavaScript validation.
  3. Valid data is sent via POST to Daraz’s backend (action="/checkout").
  4. Server processes the order and returns a confirmation page.

2. Client-Side Validation Techniques

Client-side validation checks user input before submission, improving UX and reducing server load. Techniques include:

sequenceDiagram
    participant User
    participant DarazForm
    participant RegexValidator
    User->>DarazForm: Enters phone: 9843276541
    DarazForm->>RegexValidator: /^[0-9]{10}$/ test
    RegexValidator-->>DarazForm: true
    DarazForm->>User: Shows ✅ (valid)
    User->>DarazForm: Enters phone: 984327654
    DarazForm->>RegexValidator: /^[0-9]{10}$/ test
    RegexValidator-->>DarazForm: false
    DarazForm->>User: Shows ❌ (invalid, 10 digits required)
Daraz’s real-time phone validation flow using regex

A. HTML5 Validation Attributes

<input type="email" placeholder="user@example.com" required>
<input type="tel" pattern="[0-9]{10}" title="10-digit phone number">
  • type="email": Validates email format (e.g., user@domain.com).
  • pattern: Uses regex (e.g., [0-9]{10} for 10-digit phone numbers).
  • title: Shows an error message if validation fails.

B. JavaScript Validation

JavaScript provides dynamic validation (e.g., real-time feedback) and custom rules (e.g., password strength).

Common Validation Rules
Rule Example Regex/Pattern Use Case
Email /^[^\s@]+@[^\s@]+\.[^\s@]+$/ Ncell’s SIM registration
Phone (Nepal) /^[0-9]{10}$/ Pathao’s driver sign-up
Password strength /^(?=.*[A-Z])(?=.*\d).{8,}$/ Bank login (min 8 chars, 1 uppercase, 1 digit)
Confirm password password === confirmPassword Daraz account creation
Worked Example: NEPSE Stock Form
function validateForm() {
  const phone = document.getElementById("phone").value;
  const email = document.getElementById("email").value;

  if (!/^[0-9]{10}$/.test(phone)) {
    alert("Invalid phone number (10 digits required)");
    return false;
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    alert("Invalid email format");
    return false;
  }
  return true; // Form submits if valid
}
  • How it works:
    1. User enters phone/email in the NEPSE trading form.
    2. On onsubmit, validateForm() runs.
    3. Regex checks format; if invalid, shows an alert and prevents submission.

C. Event-Based Validation

Use JavaScript events to validate as the user types:

<input type="text" id="username" onblur="validateUsername()">
  • onblur: Validates when the field loses focus.
  • onchange: Validates when the value changes.
  • onsubmit: Validates before form submission.
Mermaid: Validation Event Flow
sequenceDiagram
    User->>Input Field: Types in phone number
    Input Field->>onblur: Triggers validatePhone()
    validatePhone()->>Regex: Checks /^[0-9]{10}$/
    Regex-->>validatePhone(): Returns true/false
    validatePhone()->>UI: Shows error message if false

3. Security Considerations

Client-side validation alone is not secure because:

  • Users can disable JavaScript (bypassing validation).
  • Browser tools (e.g., DevTools) can modify form data.
  • Malicious users can send raw HTTP requests (e.g., changing a Daraz order quantity to 9999).

Best Practices for Secure Forms

Practice Example
Always validate on the server Ncell checks phone numbers against its database.
Use HTTPS eSewa’s payment forms use https:// to encrypt data.
Sanitize inputs Remove <script> tags from user comments (XSS protection).
CSRF tokens Include hidden tokens (e.g., csrf_token) in forms.
Real-World Failure: Kathmandu Traffic Route Form
  • Issue: A city’s online traffic route suggestion form used only client-side validation.
  • Exploit: Hackers submitted fake routes via disabled JS, causing traffic chaos.
  • Fix: Added server-side checks to verify routes against a database of valid paths.

4. Comparison: Client-Side vs. Server-Side Validation

Feature Client-Side Validation Server-Side Validation
When it runs Before form submission (browser) After form submission (server)
Performance Faster (no server round-trip) Slower (requires server processing)
Security Weak (can be bypassed) Strong (enforced)
Use Case Improve UX (e.g., real-time feedback) Ensure data integrity (e.g., bank transactions)
Example Daraz’s address autocomplete Ncell’s SIM verification via database
Client-SideUX (Speed)Server-SideSecurity (Integrity)
Validation layers: Client-side improves UX, but server-side enforces rules (e.g., Ncell’s phone validation against its database)

5. Advanced: Form Handling Libraries

For complex forms (e.g., multi-step checkout in Khalti), use libraries:

  • Formik (React): Manages form state and validation.
  • React Hook Form: Optimized for performance.
  • jQuery Validation Plugin: Simplifies validation rules.
Example: Khalti Payment Form with Formik
import { useFormik } from 'formik';

const formik = useFormik({
  initialValues: { amount: '', phone: '' },
  validate: (values) => {
    const errors = {};
    if (!/^[0-9]{10}$/.test(values.phone)) {
      errors.phone = "Invalid phone number";
    }
    return errors;
  },
  onSubmit: (values) => {
    // Send to Khalti's API
  }
});

In the Real World

  1. eSewa Payment Forms

    • Idea Used: Client-side validation for phone number (10 digits) and amount (numeric only).
    • How: Uses type="tel" and pattern="[0-9]{10}" to guide users before submission.
    • Security: Server-side validation confirms the phone is registered with eSewa.
  2. Pathao Driver Sign-Up

    • Idea Used: Real-time validation for license number format (/^[A-Z]{2}[0-9]{4}$/).
    • How: Shows an error if the license doesn’t match Nepal’s format (e.g., KH1234).
    • Impact: Reduces invalid submissions by 40%.
  3. Ncell SIM Registration

    • Idea Used: Combined validation (client-side for format, server-side for duplicate checks).
    • How:
      • Client checks phone number is 10 digits.
      • Server checks if the number is already registered.
    • Result: Prevents duplicate SIMs and fraud.
  4. Daraz Order Queue

    • Idea Used: Priority validation for high-value orders (e.g., quantity <= 100).
    • How: JavaScript checks if (quantity > 100) { showWarning(); } before submission.
    • Why: Prevents abuse of bulk ordering discounts.

Exam Tip

  1. For coding questions:

    • Always include HTML form structure (<form>, <input>, action, method).
    • Write JavaScript validation with:
      • Regex for phone/email/password.
      • onsubmit or onblur event handlers.
      • Example:
        function validate() {
          let isValid = true;
          const email = document.getElementById("email").value;
          if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            alert("Invalid email!");
            isValid = false;
          }
          return isValid;
        }
        
  2. For theoretical questions:

    • Advantages of client-side validation:
      • Faster feedback (UX).
      • Reduces server load.
    • Disadvantages:
      • Not secure alone (must combine with server-side).
      • Can be disabled by users.
    • Comparison table: Always draw a table like the one above for marks.
  3. Common pitfalls:

    • Forgetting return false in onsubmit to block invalid forms.
    • Using GET instead of POST for sensitive data (e.g., passwords).
    • Not escaping user input (risk of XSS attacks).
  4. Real-world tie-ins:

    • Relate examples to Nepali apps (eSewa, Khalti, Daraz) or global platforms (Google Forms, WhatsApp login).
    • Example answer snippet:

      "Like eSewa’s payment form, client-side validation ensures users enter a valid 10-digit phone number before submission, but the server must also verify the number exists in eSewa’s database to prevent fraud."


stateDiagram-v2
    [*] --> User_Enters_Data
    User_Enters_Data --> Client_Side_Validation
    Client_Side_Validation --> Valid: Form_Submits
    Client_Side_Validation --> Invalid: Show_Error
    Form_Submits --> Server_Side_Validation
    Server_Side_Validation --> Valid: Process_Data
    Server_Side_Validation --> Invalid: Show_Error
    Process_Data --> [*]

In the real world

  • eSewa Payment Forms: Uses HTTPS + server-side validation to ensure transaction amounts (e.g., ₹500) are processed securely, even if a user disables JavaScript. Client-side checks (e.g., type="number") provide instant feedback.
  • Pathao Driver Sign-Up: Combines HTML5 pattern (e.g., /^[0-9]{10}$/ for phone numbers) with server-side checks against NTC’s registered vehicle database to prevent fake accounts.
  • NEPSE Trading Platform: Validates stock codes (e.g., NTC or NMB) via client-side regex (e.g., /^[A-Z]{3,4}$/) but server-side verifies against the Nepal Stock Exchange’s live trading symbols to block invalid entries.

Based on the TU BITM syllabus for Web Technology I (IT237), unit 6.

Discussion

Loading…