Web TechnologyUnit 313 min read
HTML Forms, Validation & JavaScript Integration
Unit 3 of Web Technology covers HTML form elements (text, checkboxes, radio buttons, dropdowns), form validation logic using JavaScript, and real-world security/usability applications. Learn to build interactive forms with client-side validation, trace event flows, and compare validation techniques.
TAKEAWAYS:
- HTML forms use elements like
<input>,<select>, and<textarea>to collect user data, with attributes likerequired,type="email", andplaceholderfor basic validation. - JavaScript validates forms client-side (before submission) using
addEventListener("submit", validateForm), checking for empty fields, correct formats (e.g., email regex), and logical constraints (e.g., age ≥ 18). - Common validation rules:
- Usernames: 4–20 alphanumeric chars, no spaces (
/^[a-zA-Z0-9]{4,20}$/). - Emails: Must contain
@and.(/^[^\s@]+@[^\s@]+\.[^\s@]+$/). - Passwords: At least 8 chars with 1 uppercase, 1 number (
/^(?=.*[A-Z])(?=.*\d).{8,}$/).
- Usernames: 4–20 alphanumeric chars, no spaces (
- Security note: Client-side validation improves UX but never replaces server-side checks (e.g., SQL injection, CSRF).
- Real-world tie: eSewa’s payment form validates card numbers (Luhn algorithm) and OTPs in JavaScript before submission.
- Exam focus: Write complete HTML+JS code for forms with all validation functions (e.g.,
validateUsername(),validateEmail()) and handle errors viaalert()or styled messages.
1. HTML Form Elements: The Building Blocks
Forms are containers for user input, defined with <form> and populated with elements like:
<form id="signupForm" action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<input type="email" id="email" name="email" placeholder="user@example.com">
<input type="password" id="password" name="password" minlength="8">
<select id="country" name="country" required>
<option value="">Select Country</option>
<option value="NP">Nepal</option>
<option value="US">USA</option>
</select>
<button type="submit">Submit</button>
</form>
Key attributes:
type: Defines input kind (text,email,password,checkbox,radio,date, etc.).required: Makes the field mandatory (basic HTML5 validation).pattern: Uses regex for format checks (e.g.,pattern="\d{5}"for ZIP codes).placeholder: Shows hint text (e.g., "Enter your email").
Visual: Common Form Elements
classDiagram
class InputElement {
+type: String (text, email, password, etc.)
+name: String
+id: String
+required: Boolean
+placeholder: String
+pattern: Regex
}
class SelectElement {
+name: String
+multiple: Boolean
+options: Option[]
}
class Option {
+value: String
+text: String
}
class Button {
+type: String (submit, reset)
}
InputElement --> "1" Button : contained in
SelectElement --> "*" Option : contains2. Form Validation: Why and How
Why validate?
- User experience: Prevents submission errors (e.g., "Password too weak").
- Data integrity: Ensures correct formats (e.g., valid email, numeric age).
- Security: Blocks malicious input (e.g., SQL injection via
<script>tags).
Validation approaches:
| Method | Where It Runs | Example Use Case | Security Risk |
|---|---|---|---|
| HTML5 validation | Browser (client-side) | type="email" auto-checks format |
None (UX only) |
| JavaScript | Browser | Custom rules (e.g., password strength) | Bypassable (disable JS) |
| Server-side | PHP/Python/Node | Final check before database storage | Required for security |
JavaScript Validation Workflow
- Attach an event listener to the form’s
submitevent. - Check each field in a function (e.g.,
validateForm()). - Show errors if validation fails (e.g.,
alert()or styled messages). - Return
falseto cancel submission if invalid.
Example: Validating a Signup Form
<form id="signupForm" onsubmit="return validateForm()">
<input type="text" id="username" name="username">
<input type="email" id="email" name="email">
<button type="submit">Sign Up</button>
</form>
<script>
function validateForm() {
// Get form values
const username = document.getElementById("username").value;
const email = document.getElementById("email").value;
// Reset previous errors
document.getElementById("error").textContent = "";
// Validate username (4-20 alphanumeric chars)
if (!/^[a-zA-Z0-9]{4,20}$/.test(username)) {
document.getElementById("error").textContent = "Username must be 4-20 alphanumeric characters.";
return false; // Cancel submission
}
// Validate email
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
document.getElementById("error").textContent = "Please enter a valid email.";
return false;
}
return true; // Proceed to submission
}
</script>
Visual: Validation Event Flow
sequenceDiagram
User->>Form: Clicks Submit
Form->>JS: validateForm()
JS->>Username: Check regex
alt Invalid
JS->>User: Show error
User->>Form: Retries
else Valid
JS->>Form: Allow submission
Form->>Server: Submit data
end3. Real-World Applications
In the Real World
eSewa Payment Forms
- Idea: Client-side validation for card numbers (Luhn algorithm) and OTPs.
- How: JavaScript checks if the 16-digit card number passes the Luhn test before allowing submission. This reduces server load and improves UX by catching errors early.
- Example: When you enter your card details, eSewa’s form validates the number format and CVV length in real-time, showing errors like "Invalid card number" without submitting.
Khalti Checkout
- Idea: Real-time email and phone validation.
- How: Uses JavaScript to validate phone numbers (10 digits, starts with 9) and email formats. If invalid, it highlights the field and prevents submission.
- Example: Typing
user@.comin the email field immediately shows "Invalid email format" without requiring a full page reload.
Daraz Order Forms
- Idea: Quantity and stock validation.
- How: JavaScript checks if the selected quantity exceeds available stock (e.g., "Only 3 left in stock!"). It also ensures the "Add to Cart" button is disabled if the quantity is invalid.
- Example: When you try to order 100 units of a product with only 5 available, Daraz’s form validates this client-side and shows a warning.
Nepal Rastra Bank (NRB) Loan Applications
- Idea: Income and age validation.
- How: Forms validate that the applicant’s age is ≥ 21 and income is ≥ NPR 50,000 (for certain loans). JavaScript calculates loan eligibility based on these inputs before submission.
- Example: If you enter an age of 18, the form displays "You must be at least 21 years old to apply."
4. Worked Example: Pathao Driver Signup Form
Scenario: Pathao’s driver signup form requires:
- A valid license number (6 uppercase letters, e.g.,
KTM123). - Age ≥ 25.
- A working phone number (10 digits, starts with 9).
Solution:
<form id="driverForm" onsubmit="return validateDriverForm()">
<label>License Plate:</label>
<input type="text" id="license" pattern="[A-Z]{3}\d{3}" required>
<label>Age:</label>
<input type="number" id="age" min="25" required>
<label>Phone:</label>
<input type="tel" id="phone" pattern="9\d{9}" required>
<button type="submit">Register</button>
<div id="error" style="color: red;"></div>
</form>
<script>
function validateDriverForm() {
const license = document.getElementById("license").value;
const age = parseInt(document.getElementById("age").value);
const phone = document.getElementById("phone").value;
const errorDiv = document.getElementById("error");
errorDiv.textContent = "";
// Validate license (e.g., KTM123)
if (!/^[A-Z]{3}\d{3}$/.test(license)) {
errorDiv.textContent = "License must be 3 letters followed by 3 digits (e.g., KTM123).";
return false;
}
// Validate age
if (age < 25) {
errorDiv.textContent = "You must be at least 25 years old.";
return false;
}
// Validate phone (10 digits, starts with 9)
if (!/^9\d{9}$/.test(phone)) {
errorDiv.textContent = "Phone must be 10 digits starting with 9 (e.g., 9812345678).";
return false;
}
return true; // Submit to server
}
</script>
Visual: Pathao License Validation Regex
License Format: [A-Z]{3}\d{3}
Example: KTM123
Breakdown:
- [A-Z]{3}: Exactly 3 uppercase letters (K, T, M)
- \d{3}: Exactly 3 digits (1, 2, 3)
5. Common Validation Patterns
| Field Type | Validation Rule | JavaScript Regex Example | Example Input |
|---|---|---|---|
| Username | 4–20 alphanumeric, no spaces | /^[a-zA-Z0-9]{4,20}$/ |
john_doe123 |
Must contain @ and . |
/^[^\s@]+@[^\s@]+\.[^\s@]+$/ |
user@example.com |
|
| Password | 8+ chars, 1 uppercase, 1 number | /^(?=.*[A-Z])(?=.*\d).{8,}$/ |
Passw0rd |
| Phone (Nepal) | 10 digits, starts with 9 | /^9\d{9}$/ |
9812345678 |
| Age | ≥ 18 (numeric) | parseInt(age) >= 18 |
25 |
| License Plate | 3 letters + 3 digits (e.g., KTM123) | /^[A-Z]{3}\d{3}$/ |
KTM123 |
| ZIP Code (US) | 5 digits | /^\d{5}$/ |
12345 |
6. Advanced: Styling Validation Errors
Instead of alert(), use CSS to highlight errors:
<style>
.error {
border: 2px solid red;
background-color: #ffeeee;
}
#error {
color: red;
font-weight: bold;
}
</style>
<script>
function validateForm() {
const username = document.getElementById("username");
const errorDiv = document.getElementById("error");
if (!/^[a-zA-Z0-9]{4,20}$/.test(username.value)) {
username.classList.add("error");
errorDiv.textContent = "Invalid username.";
return false;
}
username.classList.remove("error");
return true;
}
</script>
Visual: Styled Error Example
classDiagram
class InputField {
+value: String
+classList: DOMTokenList
+add(error): void
+remove(error): void
}
class ErrorMessage {
+textContent: String
+style: CSS
}
InputField --> ErrorMessage : displays errors7. Security Considerations
Client-side validation is NOT secure!
- Why? Users can disable JavaScript or modify form data before submission.
- Solution: Always validate server-side (e.g., PHP, Node.js) for:
- SQL injection (e.g.,
name=' OR '1'='1). - Cross-Site Scripting (XSS) (e.g.,
<script>alert('hack')</script>). - Malformed data (e.g., negative ages).
- SQL injection (e.g.,
Example: Server-Side PHP Validation
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$email = $_POST["email"];
// Sanitize inputs
$username = htmlspecialchars($username);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format.");
}
// Store in database (with prepared statements to prevent SQL injection)
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->execute([$username, $email]);
}
?>
8. Exam Tip: How to Score Full Marks
Structure your answer:
- Start with
<!DOCTYPE html>and<html>tags. - Include all required elements (e.g.,
<form>,<input>,<script>). - Use proper indentation for readability.
- Start with
Validation functions:
- Write separate functions for each field (e.g.,
validateUsername(),validateEmail()). - Return
falseif validation fails,trueif valid.
- Write separate functions for each field (e.g.,
Error handling:
- Use
document.getElementById("error").textContentto show messages. - Highlight invalid fields with CSS (e.g.,
border: 2px solid red).
- Use
Common pitfalls:
- Forgetting
return falsein the validation function (form will submit anyway). - Not escaping user input (always sanitize server-side).
- Using
alert()without styling (examiners prefer styled messages).
- Forgetting
Past exam patterns:
- Expect questions on combining HTML forms with JavaScript validation.
- Be ready to validate textboxes, dropdowns, radio buttons, and checkboxes.
- Include realistic validation rules (e.g., age ≥ 18, email format).
9. Practice Questions (Self-Check)
Create a form with:
- A textbox for "Book Title" (required, max 50 chars).
- A dropdown for "Genre" (e.g., Fiction, Non-Fiction).
- A checkbox for "Subscribe to newsletter". Write JavaScript to validate:
- Title is not empty and ≤ 50 chars.
- Genre is selected.
- Show errors if invalid.
Extend the Pathao driver form to:
- Validate the license plate starts with
KT(e.g.,KT1234). - Ensure the phone number is unique (simulate with a hardcoded list like
["9812345678", "9898765432"]).
- Validate the license plate starts with
Write a form for a Nepal Electricity Authority (NEA) bill payment:
- Fields: Customer ID (6 digits), Amount (numeric, ≥ 100), Payment Method (cash/online).
- Validate:
- Customer ID is 6 digits.
- Amount is ≥ 100.
- Payment method is selected.
- Style errors in red.
10. Summary Table: Validation Methods
| Method | Pros | Cons | Use Case |
|---|---|---|---|
| HTML5 Validation | No JS needed, simple | Basic checks only | Quick UX feedback (e.g., required) |
| JavaScript | Custom rules, real-time | Bypassable, no security | Complex logic (e.g., password strength) |
| Server-Side | Secure, final check | Slower, requires backend | All critical validations |
Based on the TU BSc CSIT syllabus for Web Technology (CSC318), unit 3.
Discussion
Loading…