Lesson 18: HTML Forms Part 4

Master form validation, accessibility, multi-step forms, and form submission methods

Start Learning

Form Validation

Form validation ensures that user input meets specific criteria before submission.

Key Insight: Use HTML5 validation attributes for basic validation and JavaScript for complex rules.

HTML5 Validation Attributes

<form id="validation-form">
  <div class="form-group">
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
  </div>
  
  <div class="form-group">
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" 
           required minlength="8">
  </div>
  
  <div class="form-group">
    <label for="age">Age:</label>
    <input type="number" id="age" name="age" 
           min="18" max="100">
  </div>
  
  <div class="form-group">
    <label for="website">Website:</label>
    <input type="url" id="website" name="website" 
           pattern="https?://.+">
  </div>
  
  <button type="submit">Submit</button>
</form>

Result:

Custom JavaScript Validation

<form id="custom-validation-form">
  <div class="form-group">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>
    <div class="error-message" id="username-error"></div>
  </div>
  
  <div class="form-group">
    <label for="confirm-password">Confirm Password:</label>
    <input type="password" id="confirm-password" name="confirm_password" required>
    <div class="error-message" id="password-error"></div>
  </div>
  
  <button type="submit">Submit</button>
</form>

<script>
document.getElementById('custom-validation-form').addEventListener('submit', function(e) {
    e.preventDefault();
    let isValid = true;
    
    // Validate username
    const username = document.getElementById('username').value;
    const usernameError = document.getElementById('username-error');
    if (username.length < 4) {
        usernameError.textContent = 'Username must be at least 4 characters';
        document.querySelector('#username').parentElement.classList.add('invalid');
        isValid = false;
    } else {
        usernameError.textContent = '';
        document.querySelector('#username').parentElement.classList.remove('invalid');
    }
    
    // Validate password match
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    const passwordError = document.getElementById('password-error');
    
    if (password !== confirmPassword) {
        passwordError.textContent = 'Passwords do not match';
        document.querySelector('#confirm-password').parentElement.classList.add('invalid');
        isValid = false;
    } else {
        passwordError.textContent = '';
        document.querySelector('#confirm-password').parentElement.classList.remove('invalid');
    }
    
    if (isValid) {
        // Form is valid, submit it
        alert('Form is valid and ready for submission!');
        // In a real app: this.submit();
    }
});
</script>

Result:

Accessibility in Forms

Creating accessible forms ensures that all users, including those with disabilities, can interact with your forms.

Key Principles: Proper labeling, keyboard navigation, clear instructions, and ARIA attributes.

Accessible Form Elements

Bad Example: Missing Labels

Screen readers can't identify what this input is for.

Good Example: Proper Labeling

ARIA Attributes for Validation

<div class="form-group">
  <label for="email-input">Email:</label>
  <input type="email" id="email-input" name="email" 
         aria-describedby="email-error"
         aria-invalid="false">
  <div id="email-error" class="error-message" 
       role="alert" aria-live="assertive"></div>
</div>

<script>
// When validation fails:
document.getElementById('email-input').setAttribute('aria-invalid', 'true');
document.getElementById('email-error').textContent = 'Please enter a valid email';
</script>

Keyboard Accessibility

Important: Ensure all form elements are keyboard navigable using the Tab key. Use tabindex appropriately.

Multi-Step Forms

Break complex forms into multiple steps to improve user experience and completion rates.

1
2
3

Personal Information

Account Setup

Preferences

<script>
// Multi-step form navigation
document.getElementById('next-step1').addEventListener('click', function() {
    document.getElementById('step1').classList.remove('active');
    document.getElementById('step2').classList.add('active');
    document.querySelector('[data-step="1"]').classList.remove('active');
    document.querySelector('[data-step="2"]').classList.add('active');
});

document.getElementById('prev-step2').addEventListener('click', function() {
    document.getElementById('step2').classList.remove('active');
    document.getElementById('step1').classList.add('active');
    document.querySelector('[data-step="2"]').classList.remove('active');
    document.querySelector('[data-step="1"]').classList.add('active');
});

document.getElementById('next-step2').addEventListener('click', function() {
    document.getElementById('step2').classList.remove('active');
    document.getElementById('step3').classList.add('active');
    document.querySelector('[data-step="2"]').classList.remove('active');
    document.querySelector('[data-step="3"]').classList.add('active');
});

document.getElementById('prev-step3').addEventListener('click', function() {
    document.getElementById('step3').classList.remove('active');
    document.getElementById('step2').classList.add('active');
    document.querySelector('[data-step="3"]').classList.remove('active');
    document.querySelector('[data-step="2"]').classList.add('active');
});

document.getElementById('multi-step-form').addEventListener('submit', function(e) {
    e.preventDefault();
    alert('Form submitted successfully!');
});
</script>

Form Submission Methods

Different ways to submit form data to a server.

Traditional Submission

Standard form submission that reloads the page.

<form action="/submit" method="POST">
  <!-- Form fields -->
  <button type="submit">Submit</button>
</form>

AJAX with Fetch API

Submit form data without page reload using JavaScript.

document.querySelector('form').addEventListener('submit', function(e) {
  e.preventDefault();
  
  fetch('/submit', {
    method: 'POST',
    body: new FormData(this)
  })
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
});

FormData API

Construct form data programmatically for submission.

const formData = new FormData();
formData.append('username', 'john_doe');
formData.append('email', '[email protected]');
formData.append('avatar', fileInput.files[0]);

fetch('/submit', {
  method: 'POST',
  body: formData
});

Practical Exercise: Complete Registration Form

Create a comprehensive registration form with validation, accessibility, and AJAX submission.

Solution: