Form Validation
\title{ Form Validation }
{Learning Objectives}
This lesson provides an overview of form validation concepts and tools using HTML and JavaScript. By the end of this lesson, learners will be able to:
Validate a form using built-in HTML validation attributes.
Create regular expressions to match strings to specified patterns.
Use JavaScript functions to validate form input based on custom logic.
{Table of Contents}
Form Validation:
Required.
Minlength and Maxlength.
Min and Max.
Type.
Pattern.
Regular Expressions.
Form Validation Code Breakdown:
Text Input.
Email Text Input.
Email Input.
Tel Input.
Date Input.
Select Element.
Password Input.
Form Element Events.
Drop-down Lists.
Select or Deselect Checkboxes using JavaScript.
{Form Validation}
Form validation is the process of ensuring that user input matches the desired parameters before that input is handled by associated functions. HTML has built-in client-side form validation to validate user data with the following attributes:
required - Specifies whether a form field needs to be filled in before the form can be submitted.
minlength and maxlength - Specifies the minimum and maximum length of textual data.
$>\min$ and max - Specifies the minimum and maximum values of numerical input types.
type - Specifies whether the data needs to be a number, an email address, or some other specific preset data type.
pattern-Specifies a regular expression that defines a pattern the entered data needs to follow.
{Form Validation: Required}
The boolean required attribute, if present, indicates that the user must specify a value for the input before the owning form can be submitted.
The required attribute is supported by text, search, url, tel, email, password, date, month, week, time, datetime-local, number, checkbox, radio, and file, 〈input> types, along with the 〈select> and form control elements. If present on any of these input types and elements, the : required CSS pseudo-class will match. If the attribute is not included, the :optional CSS pseudo-class will match.
{Enter Name}
Please fill out this field.
{Form Validation: Minlength and Maxlength}
The minlength attribute defines the minimum number of characters (as UTF-16 code units) the user can enter into an or . This must be an integer value of $\theta$ or higher. If no minlength is specified, or an invalid value is specified, the input has no minimum length. This value must be less than or equal to the value of maxlength; otherwise, the value will never be valid, as it is impossible to meet both criteria.
The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an or . This must be an integer value of $\theta$ or higher.
{a}
Please lengthen this text to 2 characters or more (you are currently using 1 character).
{Form Validation: Min and Max}
The min attribute defines the minimum value that is acceptable and valid for the input containing the attribute. If the value of the element is less than this, the element fails constraint validation. This value must be less than or equal to the value of the max attribute.
The max attribute defines the maximum value that is acceptable and valid for the input containing the attribute. If the value of the element is greater than this, the element fails constraint validation. This value must be greater than or equal to the value of the min attribute.
It is valid for the input types date, month, week, time, datetime-local, number, and range, as well as the element.
Value must be greater than or equal to 2.
{Form Validation: Type}
How an element works varies considerably depending on the value of its type attribute:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-08.jpg%3Fheight%3D889%26width%3D2382%26top_left_y%3D442%26top_left_x%3D40&width=768&dpr=4&quality=100&sign=ddc932d3&sv=1)
{Form Validation: Pattern}
The pattern attribute specifies a regular expression the form control's value should match. If a non-null value does not conform to the constraints set by the pattern value, the Validitystate object's read-only patternMismatch property will be true.
Using the title attribute in conjunction with the pattern attribute will let you achieve a custom message to help users identify what is expected for the current input. Without a title attribute or the appropriate type attribute, your input requirements could be difficult to understand.
Country code: Not a Country Code
! Please match the requested format.
Three letter country code
{Regular Expressions}
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects.
These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), replaceAll(), search(), and split() methods of String.
There are two ways to create regular expressions: by using a regular expression literal, which consists of a regular expression pattern enclosed between forward slashes; or by calling the constructor function of the Regexp object.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-10.jpg%3Fheight%3D278%26width%3D1622%26top_left_y%3D871%26top_left_x%3D292&width=768&dpr=4&quality=100&sign=71b3fe0b&sv=1)
{Regular Expressions: Practice Tools}
To practice building regular expressions, try these four tools when you have time to experiment:
{RegExr}
An online tool to learn, build, and test regular expressions, with the ability to see what portions of text match the expressions in real time. Includes a visual representation of the regex statement.
$>\quad$ Regex 101
A tool to create and test regular expressions, with a built-in display of matching information as well as an explanation section to elaborate upon how the regex works.
Regex Learn
An interactive regex tutorial that walks through increasing complexities. Includes a playground and a handy cheat sheet.
{ExtendsClass Regex Tester}
Another visual regex tester with a different method of displaying results.
{Form Validation Code Breakdown}
Using the provided code within form-validation.html, we will discuss some elements and attributes of form validation, including types and regular expressions.
The contents of this example file have also been included to the right for reference, excluding DOCTYPE and html tags.
The following slides will analyze this code in detail.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-12.jpg%3Fheight%3D1308%26width%3D1078%26top_left_y%3D19%26top_left_x%3D1419&width=768&dpr=4&quality=100&sign=ef3ea2f5&sv=1)
{Code Breakdown: Text Input}
Consider the above element:
The above input element has a type attribute of "text" and a pattern attribute with a regular expression value of $\wedge[a-z A-Z]+$.
$>\wedge$ matches the beginning of the string, or the beginning of a line if the multiline flag is enabled.
$>+$ matches the previous token ( $[a-z A-Z]$ ) one or more times, as many times as possible.
$>a-z$ matches a single character in the range between a (index 97) and $z$ (index 122) (case sensitive).
$>A-Z$ matches a single character in the range between $A$ (index 65) and $Z$ (index 90) (case sensitive).
{Code Breakdown: Email Text Input}
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-14.jpg%3Fheight%3D195%26width%3D1732%26top_left_y%3D363%26top_left_x%3D145&width=768&dpr=4&quality=100&sign=9ad631b4&sv=1)
Consider the above element:
The second input as shown above, has a type attribute of text and a pattern attribute with a regular expression value of $\wedge \mid w+([.-]$ ? $\backslash w+) * @ \mid w+([.-]$ ? $\backslash w+) *(\backslash . \backslash w{2,3})+$$.
Each capturing group (a section contained between parentheses) highlighted above will be analyzed separately in the coming slides.
\title{ Code Breakdown: Email Text Input (continued) }
\author{ <input type="text" name="Email" placeholder="Email with RegEx" \ title="Please start with a letter and follow name@mail.com"
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-15.jpg%3Fheight%3D73%26width%3D1716%26top_left_y%3D483%26top_left_x%3D153&width=768&dpr=4&quality=100&sign=692a2f60&sv=1)
Consider the section $\wedge \mid w+$ :
$>\wedge$ matches the beginning of the string.
Iw matches any word character (equivalent to [a-zA-zo-9_]).
$>+$ matches the previous token one or more times, as many times as possible.
This section looks for any number of consecutive word characters at the beginning of the string.
\title{ Code Breakdown: Email Text Input (continued) }
\author{ <input type="text" name="Email" placeholder="Email with RegEx" \ title="Please start with a letter and follow name@mail.com"
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-16.jpg%3Fheight%3D74%26width%3D1716%26top_left_y%3D483%26top_left_x%3D153&width=768&dpr=4&quality=100&sign=dee2bcdc&sv=1)
Consider the capturing group $([.-]$ ? $(w+) *$ :
Looking for a character in the list [. - ]
? matches the previous token zero times or once.
Iw matches any word character (equivalent to [a-zA-z0-9_]).
$>+$ matches the previous token one or more times, as many times as possible.
$>*$ matches the previous token zero or more times, as many times as possible.
This capturing group looks for an instance of . or - zero times or once, followed by any word character one or more times. It then attempts to match that pattern zero or more times. This allows for dots and slashes to appear in an email address, but not more than once in a row.
\title{ Code Breakdown: Email Text Input (continued) }
\author{ <input type="text" name="Email" placeholder="Email with RegEx" \ title="Please start with a letter and follow name@mail.com"
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-17.jpg%3Fheight%3D73%26width%3D1716%26top_left_y%3D483%26top_left_x%3D153&width=768&dpr=4&quality=100&sign=aab47aca&sv=1)
Consider the section @ $\backslash w+$ :
$>@$ matches the character @.
Iw matches any word character (equivalent to [a-zA-z0-9_]).
$>+$ matches the previous token one or more times, as many times as possible.
This section looks for an @ symbol followed by any number of consecutive word characters.
\title{ Code Breakdown: Email Text Input (continued) }
\author{ <input type="text" name="Email" placeholder="Email with RegEx" \ title="Please start with a letter and follow name@mail.com"
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-18.jpg%3Fheight%3D74%26width%3D1716%26top_left_y%3D483%26top_left_x%3D153&width=768&dpr=4&quality=100&sign=722af2a2&sv=1)
Consider the capturing group $([.-] \text { ? } \backslash \mathrm{W}+)^{*}$ :
Looking for a character in the list [. - ]
? matches the previous token zero times or once.
Iw matches any word character (equivalent to [a-zA-z0-9_]).
$>+$ matches the previous token one or more times, as many times as possible.
$>*$ matches the previous token zero or more times, as many times as possible.
This capturing group looks for an instance of . or - zero times or once, followed by any word character one or more times. It then attempts to match that pattern zero or more times. This allows for dots and slashes to appear in the email domain, but not more than once in a row.
\title{ Code Breakdown: Email Text Input (continued) }
\author{ <input type="text" name="Email" placeholder="Email with RegEx" \ title="Please start with a letter and follow name@mail.com"
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-19.jpg%3Fheight%3D73%26width%3D1716%26top_left_y%3D483%26top_left_x%3D153&width=768&dpr=4&quality=100&sign=48c7f304&sv=1)
Consider the capturing group $(1 . \mid w{2,3})+$$ :
Looking for the character. (escaped via a backslash).
Iw matches any word character (equivalent to [a-zA-z0-9_]).
$>{2,3}$ matches the previous token two or three times.
$>+$ matches the previous token one or more times, as many times as possible.
$>$$ matches the end of the string.
This capturing group looks for an instance of ., followed by any word character two or three times. It then attempts to match that pattern one or more times at the end of the string. This checks for the end of an email domain, such as "example.com."
{Code Breakdown: Email Input}
<input type="email" name="EmailTwo" placeholder="Email with type email" required/〉
The complexity of the previous text input regular expression can be simplified with an input of the email type. This input type comes with built-in validation that will ensure the email is correct while also providing the user with messages to aid them in achieving the correct format.
These images provide a couple of examples of these validation messages, but the email input type has many more messages it can produce.
name@
Please enter a part following '@'. 'name@' is incomplete.
Please include an '@' in the email address. 'name' is missing an '@'.
{Code Breakdown: Tel Input}
<input type="tel" name="Zip" min="5" maxlength="5" id="ZipID"
placeholder="Enter Zip Code" pattern="\d{5}" title="Five digits only" required/>
This input element has a type attribute value of tel and a regular expression of $\backslash d{5}$.
Type tel helps when using mobile devices, as it will show a custom keypad optimized for entering phone numbers.
The regular expression section $\backslash d$ matches a digit (equivalent to [0-9]), and ${5}$ matches the previous token exactly five times, effectively creating validation for a five-digit zip code. However, this will not validate that the zip code actually exists.
{Code Breakdown: Date Input}
This input element has a type attribute value of date.
The date type will create an input field that allows the user to enter a date either through a textbox that validates the input or a special date picker interface.
The min and max values specify a range of acceptable dates, and the value attribute sets the starting date of the field. By default, the value is empty.
{Code Breakdown: Select Element}
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-23.jpg%3Fheight%3D362%26width%3D1721%26top_left_y%3D365%26top_left_x%3D149&width=768&dpr=4&quality=100&sign=9c849a6c&sv=1)
The 〈select element represents a control that provides a menu of options for the user to select from. Each option is defined by anelement nested within the element. The 〈select> element has unique attributes that can be used to control it, such as multiple, which specifies whether multiple options can be selected at once; and size, which specifies how many options should be shown at once. It also accepts most of the general element attributes such as required, disabled, autofocus, etc.
{Code Breakdown: Password Input}
This input element has a type attribute value of password.
The password input is presented as a one-line plain text editor in which the text is obscured so that it cannot be read, usually by replacing each character with a symbol such as an asterisk or a dot.
{Form Element Events}
The <form> element and the <input> element can have JavaScript functions tied into them via the elements' oninput, onchange, and onsubmit attributes. This enables validation in different contexts and at different times during the form submission process.
been changed. For example, each time an individual character of a longer string is typed into a text input, this event fires.
changed, but only when the change has been completed and committed. For example, when a string is finished being typed into an input and the user moves to the next field, this event fires. onsubmit - Fires when the user submits the form through the use of a submit button or by pressing enter. The onsubmit event fires only on the <form> element itself, and not on any <input> or <button> element inside it.
You can also access these events through the addEventListener() method.
{Activity: Form Validation with JavaScript (1)}
In the next few slides, we will walk through the steps to create additional validation parameters using JavaScript alongside the built-in HTML form validation options.
Step 1: Create js file named validation.js using notepad or IDE and add the following code.
validateEmail( ) is a custom function which contains code for email validation.
An email address must contain at least an @ sign and a dot (.).
The @ sign must not be the first character of the email address, and the last dot must at least be one character after the @ sign.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-26.jpg%3Fheight%3D625%26width%3D992%26top_left_y%3D666%26top_left_x%3D1392&width=768&dpr=4&quality=100&sign=d1da8085&sv=1)
{Activity: Form Validation with JavaScript (2)}
Step 2: Include the following additional validation function within your file. This code checks whether or not certain inputs are empty, and will alert the user to provide that information.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-27.jpg%3Fheight%3D810%26width%3D1149%26top_left_y%3D490%26top_left_x%3D76&width=768&dpr=4&quality=100&sign=e4ea2ae8&sv=1)
{Activity: Form Validation with JavaScript (3)}
Step 3: Create a file named form.html using notepad or an IDE, and add the following code.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-28.jpg%3Fheight%3D841%26width%3D1740%26top_left_y%3D458%26top_left_x%3D372&width=768&dpr=4&quality=100&sign=d64a79b3&sv=1)
{Activity: Form Validation with JavaScript (4)}
Step 4: Open form.html using your browser. You will see the form we created.
Try submitting the form with no data, or with certain fields empty. You should get an error message sent by our JavaScript code. The error should bring you to the field that needs attention.
Providing an invalid email format also produces an error message due to our validateEmail() function. It is in this way that you can leverage JavaScript to create custom validation and error reporting for specific use cases.
\begin{tabular}{|l|} \hline Enter Name \ \hline Enter Email \ \hline Enter Zip Code \ \hline [choose yours] I Select Country $\checkmark$ \ \hline Password \ \hline Submit \ \hline \end{tabular}
Click here to download the completed code for this example activity.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-29.jpg%3Fheight%3D271%26width%3D874%26top_left_y%3D917%26top_left_x%3D708&width=768&dpr=4&quality=100&sign=90920f71&sv=1)
This page says
Please enter correct email ID
{Activity: Create a Form with Validation}
Create the form below using HTML and CSS, and then add validation to it using built-in HTML validation, as well as JavaScript validation functions.
{Register}
Please provide your information below.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-30.jpg%3Fheight%3D64%26width%3D230%26top_left_y%3D775%26top_left_x%3D558&width=768&dpr=4&quality=100&sign=aa652266&sv=1)
Password
Repeat Password
{Login}
Login using your account information.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-30.jpg%3Fheight%3D157%26width%3D660%26top_left_y%3D776%26top_left_x%3D1245&width=768&dpr=4&quality=100&sign=fff1171f&sv=1)
Keep me logged in.
Login
{Drop-down Lists}
A drop-down list is a toggleable menu that allows the user to choose one option from multiple. A drop-down list typically only allows for one selection.
{Important points:}
The <select> tag is used with the <option> tag to create a simple drop-down list in HTML, and after that, JavaScript helps to perform operations with the list.
You can also use the container tag $\langle$ div $\rangle$ to create a drop-down list by making use of CSS. Add the drop-down items and links inside it.
You can use any element, such as 〈button〉, $\langle a\rangle$, or $\langle p\rangle$ to open a drop-down menu.
\begin{tabular}{|l|l|} \hline Select your favourite location for vacation: & -- Choose Location--- $\vee$ \ Your preferred vacation site is: & ---Choose Location-- \ & Florida \ & New York \ & Hollywood \ & Texas \end{tabular}
Select your favourite location for vacation: New York
Your preferred vacation site is: New York
{Drop-down Lists - Example}
The following code creates the example shown on the previous page, also included below.
$\langle$ html $\rangle$
$\langle$ head $\rangle$
$\langle$ title〉Drop-down Menu</title
$\langle/$ head $\rangle$
<scipt
function mydropdown() {
var mylist = document.getElementById("myList");
document.getElementById("favourite"). value =
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-32.jpg%3Fheight%3D293%26width%3D1081%26top_left_y%3D568%26top_left_x%3D1296&width=768&dpr=4&quality=100&sign=fafde963&sv=1)
Select your favourite location for vacation: New York
Your preferred vacation site is: New York
{Select or Deselect Checkboxes Using JavaScript}
In this example, we will demonstrate how to select or deselect all or some checkboxes using JavaScript. We will create two buttons: one for selecting all checkboxes, and the other for deselecting all of the selected checkboxes.
Examples of the results of each of these functions are included below.
Clicking the "Select All" Button
Select or Deselect all or some checkboxes to describe your mood:
Happy
Sad
Excited
Angry
Select All Deselect All Clicking the "Deselect AII" Button
Select or Deselect all or some checkboxes to describe your mood:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-33.jpg%3Fheight%3D239%26width%3D345%26top_left_y%3D920%26top_left_x%3D1288&width=768&dpr=4&quality=100&sign=76fbb441&sv=1)
{Select or Deselect Checkboxes - Example}
The following code creates the example shown on the previous page, also included to the right.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-34.jpg%3Fheight%3D812%26width%3D1183%26top_left_y%3D442%26top_left_x%3D152&width=768&dpr=4&quality=100&sign=8c9dc8f2&sv=1)
{PA: Form Validation}
Please follow the links below to the practice assignment for form validation:
PA - 308.5.1 - Form Validation
You can also find this assignment on Canvas under the Assignments section.
If you have technical questions while performing the activity, ask your instructors for assistance.
{Knowledge Check}
How does the required attribute help with validating a form?
How does the maxlength attribute help with validating a form?
How does the pattern attribute help with validating a form?
How does the email type attribute help with validating a form?
What is a regular expression?
How do you create a regular expression variable in JavaScript?
What elements are used to create a standard drop-down list in HTML?
When using JavaScript to validate a form, what attribute(s) should you assign the JavaScript function to?
{Summary}
Form validation is the process of ensuring that user input matches the desired parameters before that input is handled by associated functions.
HTML has built-in attributes to aid in client-side form validation, such as required, minlength and maxlength, min and max, type, and pattern.
Regular expressions can be used with the pattern attribute, as well as other JavaScript functions, to ensure that strings of text match specified patterns.
The type attribute can be used to simplify validation using built-in parameters, as well as to provide accessibility in the form of custom input fields on varying devices.
JavaScript functions can be tied into form elements' oninput, onchange, and onsubmit attributes to provide validation in different ways and during different times in the submission process.
Dropdown lists and checkboxes provide powerful options for creating forms and interactive elements, and can be manipulated with JavaScript functions and events.
{Questions?}
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_35623d06f431ea0bec38g-39.jpg%3Fheight%3D756%26width%3D749%26top_left_y%3D438%26top_left_x%3D735&width=768&dpr=4&quality=100&sign=a69729af&sv=1)
Last updated