Welcome to today's session, where we will focus on form validation, a critically vital aspect of web development. Consider web forms as doorways that allow users to interact with web applications—whether registering for accounts or submitting requests. However, if we were to permit any input in these forms, chaos could ensue. Hence, we mitigate this issue by employing form validation. In this session, we'll master HTML attributes such as required, type, minlength, maxlength, min/max, understand regular expressions (regex), study the pattern attribute, and learn how JavaScript validates forms.
HTML form input attributes give us the power to validate user input right in the browser, serving as our first line of defense in form validation. Let's dissect these attributes:
required: This attribute ensures the user supplies input in a necessary field.type: Specifies the kind of data the user must input (e.g., text, email, number, etc.).minlengthandmaxlength: These constraints limit the length of user input.minandmax: These set the range for numerical input.title: Displays advisory information about the element it belongs to, providing a hint to the user about how to fill out the input or what kind of data is expected.
As an illustration, consider the following password input field, which enforces a password length minimum of 8 characters and a maximum of 20 characters while providing a tooltip when the user hovers over the input field. Note that with the required attribute, the password field cannot be empty:
Here is a different number input field, where the min and max attributes specify that the permissible range for this input is between 1 and 10, inclusively:
Regular expressions, or regex, are sequences of characters that form a search pattern used for text searching and text replacing operations. In HTML forms, regex patterns allow us to match and validate various input strings (such as phone numbers, zip codes) using the pattern attribute. This is best explained by the following example:
This phone number form input requires "three numbers, a dash, and then four numbers" to submit the form.
