Overview

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.

Getting to Know HTML Form Attributes

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.).
  • minlength and maxlength: These constraints limit the length of user input.
  • min and max: 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:

<input type="password" name="password" required minlength="8" maxlength="20" title="Your password should be 8-20 characters long.">

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:

<input type="number" name="quantity" min="1" max="10" title="Enter a number between 1 and 10">
Basic Introduction to Regular Expressions (`regex`) And The `pattern` Attribute

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:

<form action="">
  Phone number (xxx-xxxx): <input type="text" name="phone" pattern="[0-9]{3}-[0-9]{4}"> <!-- pattern="[0-9]{3}-[0-9]{4}" is regex that requires the form input to be "three numbers, a dash, and then four numbers". -->
  <input type="submit">
</form>

This phone number form input requires "three numbers, a dash, and then four numbers" to submit the form.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal