Web Technology IUnit 68 min read
Form Handling & Client-Side Validation: Techniques, Events & Security
Unit 6 of Web Technology I covers how to design interactive forms, process user input, validate data before submission, and implement client-side security—key skills for building secure, user-friendly web applications like eSewa’s payment forms or Daraz’s checkout.
Core Concepts
What is Form Handling?
Forms are the primary interface for user input on the web. They collect data (text, numbers, selections) and send it to a server for processing. Key components:
- Form element (
<form>): Container for input fields. - Input fields: Text, checkboxes, radio buttons, dropdowns, etc.
- Submit button: Triggers data submission to the server.
- Action attribute: URL where form data is sent (e.g.,
action="/submit"). - Method attribute: HTTP method (
GETorPOST).
Client-Side Validation: Why and How?
Client-side validation checks user input before sending it to the server. This improves:
- User experience (immediate feedback).
- Performance (reduces unnecessary server requests).
- Security (basic filtering of malicious input).
Types of Validation:
| Type | Example | HTML5 Attribute/Method |
|---|---|---|
| Required Field | Username field must not be empty | required |
| Format Check | Email must match user@example.com |
type="email" or JavaScript regex |
| Range Check | Age must be 18–65 | min="18" max="65" |
| Pattern Match | Phone number: 98XXXXXXXX |
pattern="[0-9]{10}" |
| Custom Logic | Password must include a number | JavaScript if statements |
Worked Example: Daraz Checkout Form Daraz’s checkout requires:
- A valid email (format check).
- A password with ≥8 characters (custom logic).
- A shipping address (required field).
<form id="checkoutForm">
<input type="email" id="email" required>
<input type="password" id="password" minlength="8" pattern=".*[0-9].*">
<input type="text" id="address" required>
<button type="submit">Place Order</button>
</form>
How Validation Works: Step-by-Step
When a user submits a form, the browser triggers validation events. Here’s the flow:
sequenceDiagram
User->>Form: Submits data (clicks button)
Form->>Browser: Checks HTML5 attributes (e.g., required, pattern)
Browser-->>Form: Returns validation errors (if any)
Form->>JavaScript: Runs custom validation (if added)
JavaScript-->>Form: Returns custom errors (e.g., "Password too weak")
alt No errors
Form->>Server: Sends data via POST
else Errors exist
Form->>User: Displays error messages
endJavaScript Validation: Deep Dive
HTML5 provides basic validation, but JavaScript adds flexibility. Common techniques:
1. Event Listeners
Attach validation to form events:
document.getElementById("checkoutForm").addEventListener("submit", function(event) {
if (!validateForm()) {
event.preventDefault(); // Stop form submission
}
});
2. Custom Validation Functions
function validateForm() {
let isValid = true;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
// Email regex check
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
alert("Invalid email format!");
isValid = false;
}
// Password strength
if (password.length < 8) {
alert("Password must be at least 8 characters!");
isValid = false;
}
return isValid;
}
3. Real-Time Validation
Validate fields as the user types (e.g., Khalti’s OTP field):
document.getElementById("otp").addEventListener("input", function() {
if (this.value.length > 6) {
alert("OTP must be 6 digits!");
this.value = this.value.slice(0, 6); // Limit to 6 chars
}
});
Security Considerations
Client-side validation is not enough—always validate on the server too! Why?
- Users can bypass client-side checks (e.g., disable JavaScript).
- Malicious input can break your app (e.g., SQL injection, XSS).
Common Vulnerabilities:
| Attack | Example | Prevention |
|---|---|---|
| SQL Injection | ' OR '1'='1 in login form |
Use parameterized queries |
| XSS (Cross-Site Scripting) | <script>alert('hacked')</script> in a comment field |
Sanitize input with libraries like DOMPurify |
| CSRF (Cross-Site Request Forgery) | Tricking a user into submitting a form they didn’t intend | Use CSRF tokens in forms |
Worked Example: Ncell Recharge Form Ncell’s recharge form must:
- Validate the mobile number format (
98XXXXXXXX). - Check if the amount is a positive number.
- Sanitize input to prevent SQL injection.
function validateRecharge() {
const phone = document.getElementById("phone").value;
const amount = document.getElementById("amount").value;
if (!/^98\d{8}$/.test(phone)) {
alert("Invalid mobile number!");
return false;
}
if (isNaN(amount) || amount <= 0) {
alert("Amount must be a positive number!");
return false;
}
return true;
}
Form Handling in Real Applications
1. eSewa: Payment Forms
- Idea Used: Client-side validation for card details (e.g., expiry date format, CVV length).
- How: JavaScript checks if the card number matches Luhn’s algorithm (a checksum formula) before submission.
- Code Snippet:
function validateCardNumber(cardNumber) { // Luhn algorithm implementation let sum = 0; let shouldDouble = false; for (let i = cardNumber.length - 1; i >= 0; i--) { let digit = parseInt(cardNumber.charAt(i)); if (shouldDouble) { digit *= 2; if (digit > 9) digit -= 9; } sum += digit; shouldDouble = !shouldDouble; } return sum % 10 === 0; }
2. Pathao: Ride Booking
- Idea Used: Real-time validation for pickup/drop locations (e.g., ensuring the drop location is within the city limits).
- How: JavaScript uses the Google Maps API to validate addresses before allowing booking.
3. NEPSE: Stock Trading Forms
- Idea Used: Range validation for share quantities (e.g., "You cannot buy 0 shares").
- How: HTML5
min="1"attribute ensures users enter a valid quantity.
Exam Tip
This unit is heavily tested in TU exams with:
- Short Questions (5 marks):
- Define client-side validation. List 3 HTML5 validation attributes.
- Compare
GETandPOSTmethods for form submission.
- Programming Questions (15–20 marks):
- Write HTML for a form with required fields, email validation, and a submit button.
- Write JavaScript to validate a password (length, special characters) and prevent submission if invalid.
- Trace the flow of a form submission with client-side validation (use a sequence diagram).
- Scenario-Based (10 marks):
- "Design a form for a bank loan application with validation for age (≥18), income (≥Rs. 50,000), and loan amount (≤50% of income)."
- "Explain how client-side validation improves the user experience of an e-commerce checkout like Daraz."
Key Focus Areas:
- HTML5 validation attributes (
required,type,pattern,min,max). - JavaScript validation (event listeners, regex, custom functions).
- Security (why server-side validation is mandatory).
- Real-world mapping (tie examples to eSewa, Khalti, Daraz, etc.).
Visual Summary:
Based on the TU BIM syllabus for Web Technology I (IT237), unit 6.
Discussion
Loading…