Lesson 18: onsubmit Event

Learn how to handle form submissions with JavaScript and implement robust validation techniques.

18.1 Understanding onsubmit Event

The onsubmit event occurs when a form is submitted. This event is essential for validating form data before sending it to the server and for processing form inputs with JavaScript.

Key points: The onsubmit event triggers when the user submits a form. By returning false in the event handler, you can prevent the form from being submitted to the server.
User Submits Form
onsubmit Triggers
Validation Check
Submit or Cancel

18.1.1 Basic Form Validation

Example 18.1: Required Field Validation

This example shows how to validate required fields using onsubmit.

// JavaScript function
function validateForm() {
    const name = document.getElementById('name').value;
    
    if (name === '') {
        alert('Name is required');
        return false; // Prevent form submission
    }
    
    return true; // Allow form submission
}

// HTML
<form onsubmit="return validateForm()">
    <label for="name">Name:</label>
    <input type="text" id="name" required>
    <button type="submit">Submit</button>
</form>
Name is required

18.1.2 Email Validation

Example 18.2: Email Format Validation

This example demonstrates email validation using regular expressions.

// JavaScript function
function validateEmail(email) {
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regex.test(email);
}

function validateForm() {
    const email = document.getElementById('email').value;
    
    if (!validateEmail(email)) {
        alert('Please enter a valid email address');
        return false;
    }
    
    return true;
}

// HTML
<form onsubmit="return validateForm()">
    <label for="email">Email:</label>
    <input type="email" id="email" required>
    <button type="submit">Submit</button>
</form>
Please enter a valid email address

18.2 Advanced Form Validation

Implement more sophisticated validation techniques with real-time feedback and error summaries.

18.2.1 Real-time Validation

Example 18.3: Real-time Feedback

This example provides immediate feedback as users fill out the form.

// JavaScript functions
function validateField(field, regex, errorElement) {
    if (regex.test(field.value)) {
        field.classList.remove('invalid');
        errorElement.style.display = 'none';
        return true;
    } else {
        field.classList.add('invalid');
        errorElement.style.display = 'block';
        return false;
    }
}

// HTML
<form onsubmit="return validateForm()">
    <div class="input-group">
        <label for="username">Username:</label>
        <input type="text" id="username" 
               oninput="validateUsername(this)">
        <div class="error" id="usernameError">
            Username must be 4-12 characters
        </div>
    </div>
    <!-- More fields -->
</form>
Username must be 4-12 characters
Password must be at least 8 characters

Please fix the following errors:

    18.2.2 Form Data Processing

    Example 18.4: Display Form Data

    This example shows how to process form data with JavaScript instead of submitting to a server.

    // JavaScript function
    function processForm(event) {
        event.preventDefault(); // Prevent form submission
        
        const formData = {
            name: document.getElementById('fullName').value,
            email: document.getElementById('contactEmail').value,
            message: document.getElementById('message').value
        };
        
        // Display form data
        const resultDiv = document.getElementById('formResult');
        resultDiv.innerHTML = `
            <h3>Form Submitted Successfully!</h3>
            <p><strong>Name:</strong> ${formData.name}</p>
            <p><strong>Email:</strong> ${formData.email}</p>
            <p><strong>Message:</strong> ${formData.message}</p>
        `;
        resultDiv.style.display = 'block';
    }
    
    // HTML
    <form onsubmit="processForm(event)">
        <!-- Form fields -->
        <div id="formResult"></div>
    </form>

    18.3 Real-World Applications

    These onsubmit event techniques are essential in many web applications. Here are practical examples:

    18.3.1 Contact Form with Validation

    Example 18.5: Complete Contact Form

    This example combines all validation techniques in a complete contact form.

    // JavaScript function
    function validateContactForm() {
        let isValid = true;
        const errors = [];
        
        // Name validation
        const name = document.getElementById('contactName').value;
        if (name === '') {
            errors.push('Name is required');
            isValid = false;
        }
        
        // Email validation
        const email = document.getElementById('contactEmail').value;
        if (!validateEmail(email)) {
            errors.push('Please enter a valid email');
            isValid = false;
        }
        
        // Message validation
        const message = document.getElementById('contactMessage').value;
        if (message.length < 10) {
            errors.push('Message must be at least 10 characters');
            isValid = false;
        }
        
        // Display errors if any
        if (!isValid) {
            const errorList = document.getElementById('contactErrorList');
            errorList.innerHTML = errors.map(e => `<li>${e}</li>`).join('');
            document.getElementById('contactValidationSummary').style.display = 'block';
        }
        
        return isValid;
    }
    
    // HTML
    <form onsubmit="return validateContactForm()">
        <!-- Form fields -->
        <div class="validation-summary" id="contactValidationSummary">
            <h4>Please fix the following errors:</h4>
            <ul id="contactErrorList"></ul>
        </div>
    </form>

    Please fix the following errors:

      18.3.2 User Registration Form

      Example 18.6: Registration Form with Password Confirmation

      This example demonstrates a user registration form with password matching validation.

      // JavaScript function
      function validateRegistration(event) {
          event.preventDefault();
          
          // Password match validation
          const password = document.getElementById('regPassword').value;
          const confirmPassword = document.getElementById('confirmPassword').value;
          
          if (password !== confirmPassword) {
              document.getElementById('passwordMatchError').style.display = 'block';
              return false;
          }
          
          // If all validations pass
          document.getElementById('regResult').innerHTML = `
              <h3>Registration Successful!</h3>
              <p>Welcome, ${document.getElementById('regName').value}!</p>
          `;
          document.getElementById('regResult').style.display = 'block';
          
          return true;
      }
      
      // HTML
      <form onsubmit="validateRegistration(event)">
          <div class="input-group">
              <label for="regPassword">Password:</label>
              <input type="password" id="regPassword">
          </div>
          <div class="input-group">
              <label for="confirmPassword">Confirm Password:</label>
              <input type="password" id="confirmPassword">
              <div class="error" id="passwordMatchError">
                  Passwords do not match
              </div>
          </div>
      </form>
      Passwords do not match