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.
- Review URLSearchParams from prerequisite course: Advanced HTML Forms – WDD 231
:valid and :invalid pseudo-classes
The :valid and :invalid pseudo-classes in CSS are used to style form elements based on
their validation state. They provide visual feedback to users about whether the input they have provided meets the
specified validation criteria. By default, form elements are considered valid unless they have validation constraints that are not met.
The :valid pseudo-class applies styles to form elements that have valid input according to the defined
validation rules. For example, if an input field is required and the user has entered a value, the field will be
considered valid, and any CSS styles defined for :valid will be applied.
The :invalid pseudo-class applies styles to form elements that have invalid input according to the defined
validation rules. For example, if an input field is required and it is empty, the field will be
considered invalid, and any CSS styles defined for :invalid will be applied.
The following attributes are available for form validation in HTML5:
required: Specifies that an input field must be filled out before submitting the form.pattern: Defines a regular expression that the input value must match.minandmax: Set the minimum and maximum values for numeric input fields.type: Specifies the type of input (e.g., email, number, url) which has built-in validation rules.minlengthandmaxlength: Define the minimum and maximum number of characters allowed in a text input field.step: Specifies the legal number intervals for numeric input fields.
Here are examples of how to use the :valid and :invalid pseudo-classes in CSS:
input:valid {
border-color: green;
}
input:invalid {
border-color: red;
}
In this example, when an input field is valid, its border color will change to green, and when it is invalid, the border color will change to red. This visual feedback helps users quickly identify which fields need attention and encourages them to correct their input.
When designing forms and validation, it's important to remember that users may make mistakes or have different levels of technical proficiency. Therefore, it's essential to provide clear and helpful error messages when validation fails. Avoid blaming the user for errors; instead, guide them on how to correct their input. Use friendly language and provide specific instructions on what needs to be fixed.
To help improve the user experience, you can restrict the valid/invalid states using the :valid and :invalid pseudo-classes in CSS to provide visual feedback to users. One way to do that is with the :focus pseudo-class: For example, only trigger the :valid/:invalid pseudo-classes when the input field is focused.
input:focus:invalid {
border-color: red;
}
Activity Instructions
- Navigate to this 📑 Form example.
- Fork the CodePen into your own CodePen account.
- Modify the example by:
- Adding HTML form validation attributes to the form elements as you see fit, e.g., required.
- Adding a field requiring the user to enter the Principle amount again for verification.
- Use JavaScript validation to immediately check if the principle amounts match and notify the user and require the principle amounts to be entered again.
- Add or modify the code additional to ensure that NaN (Not a Number) output does NOT occur.
- Add CSS form element pseudo-classes valid and invalid to visually indicate that individual fields passed validation.
Optional Resources
- HTML Forms – MDN
- Using built-in form validation – MDN
- Validating forms using JavaScript – MDN
- Form properties and methods – javascript.info
- Prevent Default and Form Events – wesbos.com