WDD 330: Web Frontend Development II

W03 Learning Activity: HTML Forms and User Input Validation

Overview

Forms provide an interface for user input and interaction. They are essential for collecting data from users, such as in contact forms, surveys, and e-commerce checkouts. HTML provides a set of elements to create forms, allowing developers to define input fields, buttons, and other controls. This activity focuses on validating user input, and enhance the user experience by ensuring that the data entered is correct and complete before submission.

Prepare

Form Validation

Form validation is the process of checking user input in a form before it is submitted to ensure that the data meets specific criteria. This can include checking for required fields, validating email addresses, ensuring that numbers are within a certain range, and more.

HTML5 introduced built-in form validation attributes that allow developers to specify validation rules directly in the HTML markup. These attributes include required, pattern, min, max, and more. When a form is submitted, the browser automatically checks these attributes and provides feedback to the user if the input does not meet the specified criteria.

Here is an example of a basic HTML form with validation:

<form id="myForm">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <label for="age">Age:</label>
  <input type="number" id="age" name="age" min="18" max="100" required>
  <button type="submit">Enter Contest</button>
</form>

In this example, the form includes an email input field that is required and a number input field for age that must be between 18 and 100. The required attribute ensures that the user cannot submit the form without filling out these fields. The min and max attributes on the age input enforce that the user enters a valid age within the specified range.

CSS can enhance the user experience by providing visual feedback for valid and invalid form inputs. The :valid and :invalid pseudo-classes can be used to style form elements based on their validation state. For example, you can change the border color of an input field to green when it is valid and red when it is invalid. This visual feedback helps users quickly identify which fields need attention.

Here is a basic example of how to use CSS pseudo-classes for form validation:

input:valid { 
  border-color: green;
}

input:invalid {
  border-color: red;
}

JavaScript can be used to enhance form validation experience by providing custom validation logic, handling complex validation scenarios, and providing real-time feedback to users. This can include checking if two fields match (e.g., password confirmation), validating input formats, and preventing form submission if the data is invalid.

Here is an example of using JavaScript to validate a form:

const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
  const email = document.getElementById('email').value;
  const age = document.getElementById('age').value;
  if (!email || !age) {
    event.preventDefault(); // Prevent form submission
    alert('Please fill out all required fields.');
  } else if (age < 18 || age > 100) {
    event.preventDefault(); // Prevent form submission
    alert('Age must be between 18 and 100.');
  }
});

The built-in JavaScript methods are commonly used and are essential building blocks for user input validation. Modern form validation builds upon them by emphasizing a defense-in-depth approach (client AND server), prioritizing excellent user experience, and often leveraging the power of specialized libraries or framework features for more complex scenarios, all while keeping accessibility in mind.

URLSearchParams

URLSearchParams is a built-in JavaScript object that provides methods to work with the query string of a URL. It allows you to easily access and manipulate the parameters in the query string, making it useful for tasks such as retrieving values from form submissions or constructing URLs with specific parameters.

Activity Instructions

  1. Navigate to this 📑Form example.
  2. Fork the CodePen into your own CodePen account.
  3. Modify the example by:
    1. Adding HTML form validation attributes to the form elements as you see fit, e.g., required.
    2. Adding a field requiring the user to enter the Principle amount again for verification.
    3. Use JavaScript validation to immediately check if the principle amounts match and notify the user and require the principle amounts to be entered again.
    4. Add or modify the code additional to ensure that NaN (Not a Number) output does NOT occur.
  4. Add CSS form element pseudo-classes valid and invalid to visually indicate that individual fields passed validation.

Optional Resources