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:

{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.

{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.

{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}

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"

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"

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"

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"

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"

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.

 name \text { name }

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}

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.

{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.

{Activity: Form Validation with JavaScript (3)}

Step 3: Create a file named form.html using notepad or an IDE, and add the following code.

{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.

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.

Email

Password

Repeat Password

{Login}

Login using your account information.

Keep me logged in.

Login

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

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 =

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:

{Select or Deselect Checkboxes - Example}

The following code creates the example shown on the previous page, also included to the right.

{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?}

Last updated