Use Sophia to knock out your gen-ed requirements quickly and affordably. Learn more
×

Forms

Author: Sophia

what's covered
In this lesson, you will learn about web forms and how they are used to collect information and data from a user to be transmitted to the server. You will learn about the form tag itself, as well as the input tag and other tags used to create the fields of the web form. Finally, you will learn about the importance of form input validation and the three methods of providing validation requirements to fields within a web form.

Specifically, this lesson will cover the following:

Table of Contents

1. Web Forms

From a developer or website owner’s perspective, the primary method of gathering input data from the user to the web server is through the use of an HTML web form. A web form is a document that provides users with an interface with fields (called form controls) for typing in text or numeric data or choosing from a list of options. Once all of the fields have been filled out, the user clicks the “Submit” button and the data gets transmitted to a server-side script. The script receives the data and selections from the form and processes them.

The typical web form that most individuals might think of is the form used to register a new account with a website. You will enter your first and last name, email, and desired username and password, choose a couple of options like your preferences, enroll in a newsletter, etc., and then click “Submit.” From there, the web server’s script for registering users receives the user’s submission, performs a validation check, generates database commands to insert the user’s information into a new user account, performs any additional setup for the new account, and finally sends an email verification informing the user of the successful account creation.

However, forms are just about everywhere. Even when you log in to a site, the username and password fields are part of a small form. The Google search engine is a small form with one text field and a couple of buttons, albeit a very stylized form.

We will take a look at how forms are constructed, the common <input> tag and its many types, as well as other form control types.

terms to know

Web Form
A document that provides users with an interface of fields for typing in text or numeric data or choosing from a list of options.

Form Controls
Elements such as checkboxes, radio buttons, and menus, which allow users to enter, select, or edit information; perform actions; or display data.


2. The Form Tag

Like a table, forms are created first by writing the <form> tags to create the form container. The <form> tag also has two required attributes.

1. The method attribute specifies the type of HTTP method to use when submitting the form. This can be either GET or POST. GET is the HTTP method normally used to “get” pages and resources from a web server; however, it is also used for nonsensitive forms as a lightweight option for sending the form. The issue with GET is that the form field’s names and the values typed by the user are sent as part of the URL request. You may recall URL parameters back in Unit 1; this is where all of the field names and values are stored, which is relatively unsecure.

The POST method is the ideal method for most other forms as it protects the data being transmitted. Once the HTTP POST request is made, the data gets encoded into the payload of the HTTP POST request. This ensures that the data gets properly encrypted when it is transmitted to the server. This only applies to web servers that do not use encryption and thus do not use the HTTPS protocol, wherein the data will still be vulnerable.

2. The action attribute is used to direct the form submission to a particular server-side script or API endpoint for processing.

The other attributes for the <form> tag are as follows:

Attribute Description
accept-charset Specifies the character encoding used for the form submission
autocomplete Specifies whether a form should allow the autocomplete feature
enctype When using the POST method, specifies how the data should be encoded

Values:
  • application/x-www-form-urlencoded: the default method of encoding form data
  • multipart/form-data: required when the form will include a file upload
name Specifies the name of the form
novalidate Specifies that the form should not attempt to validate the user-provided data before submitting the form
target Specifies whether the response from the web server is to be displayed in the same window, the parent, a new tab, or a frame; works the same as the anchor tag’s target attribute

terms to know

Method Attribute
The HTML attribute for a <form> tag that specifies what HTTP method to use when transmitting the form data.

Payload
The portion of a network packet that contains the actual data being transmitted and is encapsulated in the packet’s header and trailer.

Action Attribute
The HTML attribute of a <form> tag that specifies what server-side script will receive and handle the form submission.


3. Form Controls

The <label> tag is the first control type to discuss as it is needed for each control within the form. The label is what the user sees next to each control. Labels are also used for accessibility as they increase the clickable area for a specific control. For example, radio buttons are rather small, and giving it a label increases where the user can click to activate the button.

EXAMPLE

The label has to be linked to the control one of two ways: the label needs to surround the control tag itself or the “for” attribute needs to be provided and given the “id” value assigned to the control.


<label>Subscribe: 
<input type="radio" name="subscribe"></label>

or


<label for="subscribe">subscribe: </label>
<input type="radio" name="subscribe" id="subscribe">

This will render as follows:

The most common set of form controls can be accessed by the same <input>. The <input> tag is a self-terminating tag, and its “type” attribute determines what type of control the field is. Regardless of the chosen type, each field in a form requires the “name” attribute in order to uniquely identify each control in the form.

The following is a list of all <input> type values:

Value Description
button Creates a clickable button
checkbox Creates a single checkbox
color Creates an RGB color picker tool for selecting a color
date or datetime-local Creates a date or date time picker tool for selecting a date or a date and time
email Creates a textbox that automatically validates the email is a valid email (not that it exists, just that it is formatted as a proper email address)
file Creates a file upload control with a browse button for selecting a file to be uploaded with the form
hidden Creates a hidden text field
image Used for creating a custom submit button from an image
month Creates a month picker tool
number Creates a textbox that only accepts numbers and includes incremental up and down buttons
password Creates a text field that replaces each character with dots as they are typed
radio Creates a round checkbox called a radio button; used together in groups to create a multiple-choice answer that only allows one selection (Checkboxes, on the other hand, allow for multi-answer questions, wherein multiple options may be chosen.)
range Creates a numeric range tool for specifying a range of values
reset Creates a button that clears the form when clicked
search Creates a textbox used for searches within a site
submit Creates a button for submitting the form
tel Creates a textbox that only accepts numbers that are formatted as a phone number
text Creates a generic textbox that accepts any text-based input
time Creates a time picker tool for selecting a particular time
url Creates a textbox that accepts valid URL values
week Creates a week picker tool for selecting a particular week

Each input type may require additional attributes such as the value attribute, which is used to set the value of a control. This could be the default value for a textbox or the meaning of when a particular checkbox is checked.

One attribute that is helpful for the user is the placeholder attribute.

EXAMPLE

The placeholder creates a statement within a text field that is written in light gray text and disappears when the user starts typing within the field.


<input type="tel" name="phone" placeholder="(000) 555-1234">

This will render as follows:

This is helpful as it demonstrates to the user what is expected in the field.

Now that you have seen how to create a web form, it’s time to practice!

try it

Directions: In this activity, you will create a new webpage called “about.html” and link to that page in your navigation menu. You will then build the about.html page using the basic HTML code structure and semantic tags. Finally, you will practice web forms by building a simple Contact Us form.

Note: At any time if you do not see the change occur, make sure to select the refresh button in the IDE.

1. Return to your StackBlitz project (from the previous lesson) and, if you have not already done so, create a new file in your project and name the file “about.html.” Add the basic HTML structure and include the header, nav, main, and footer semantic tags.

2. In the head, make sure to include and complete the <title> tag, the two <meta> tags, and link to the external stylesheet:


<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Harvest Bakery - About Us</title>
<link href="style.css" rel="stylesheet">

3. From the index.html file, highlight and copy all of the code between the two <nav> tags. Return to the about.html that you are working on, place your insertion point between the <nav> tags, and paste the code. (Now is a good time to double-check that the anchor tag for the “About” hyperlink is pointing to the correct file: <href="about.html">. If you had to make a change, remember to also update the navigation menu on the homepage as well.)

hint

When you click the refresh button, you may default to the homepage (index.html) of your project. To see the results of your about.html file, you will need to click on the “About” hyperlink located in the nav menu. This is why it is important that your nav link points to the correct about.html file.

This is the expected output:

The image shows a split view with HTML code on the left and a webpage preview on the right. In the HTML code, the structure begins with the <!DOCTYPE html> declaration and opening <html> tag. The <head> section includes meta tags for character encoding (utf-8), viewport settings for responsive design, and a title that reads "Harvest Bakery – About Us." There is also a link to an external stylesheet (styles.css) for additional styling. In the <body> section, there is a <header> element with a placeholder "Header" and a <nav> element that contains an unordered list (<ul>). This list has three links (<a>) to "Home," "About," and "Menu" pages, each within a list item (<li>). The layout also includes a <main> section and a <footer>, both with placeholder text ("Main" and "Footer"). On the right side, in the webpage preview, the navigation bar displays the links "Home," "About," and "Menu" in a horizontal row with a yellow background. The "About" link is highlighted with a darker yellowish-brown background, and a cursor is hovering over it. At the top of the page, there is an image of pastry buns, representing the header area. Below the navigation, the "Section" and "Main" placeholders are visible. The "Main" section contains a table labeled "Hours of Operations," showing the bakery's operating hours: Monday to Friday from 8 am to 8 pm, Saturday from 8 am to 2 pm, and Sunday as closed. The design is simple and functional, with a clear layout and interactive navigation.

The image shows a split view with HTML code on the left and a webpage preview on the right. On the left side, the HTML code includes the basic structure of a webpage. It begins with the <!DOCTYPE html> declaration and the opening <html> tag. The <head> section contains meta tags for character encoding (utf-8) and viewport settings for responsive design, a title for the page that reads "Harvest Bakery – About Us," and a link to an external stylesheet (styles.css) for applying additional styling to the webpage. In the <body> section, there is a placeholder <header> tag containing "Header" and a <nav> element, which holds an unordered list (<ul>) with three list items (<li>). Each list item contains an anchor link (<a>) to "Home," "About," and "Menu" pages. The layout also includes placeholder <main> and <footer> sections. On the right side, the webpage preview shows the navigation bar with the links "Home," "About," and "Menu," displayed in a horizontal row with a yellow background. The links are styled with blue, underlined text, and the background extends across the navigation area. The rest of the page is blank, with no content yet displayed below the navigation bar. The webpage layout is simple, focusing on the navigation bar for now, with no additional sections yet populated.

4. Within the main section of the About page, include an <h1> element, and within it include a message like “Learn a little about us!” or “Our Story:”.

5. Below the <h1> element, create a <p> paragraph and include some Lorem Ipsum (you can grab some Lorem Ipsum text using a Lorem Ipsum generator website.

6. Below the paragraph you just created, add a <h2> heading element and give it the text “Contact Us.”

This is the expected output:

The image shows a split view with HTML code on the left and a webpage preview on the right. On the left side, the HTML code outlines the structure of the "About Us" page. The code starts with a <!DOCTYPE html> declaration, followed by the opening <html> tag. The <head> section includes meta tags for character encoding (utf-8) and viewport settings for responsive design, a title that reads "Harvest Bakery – About Us," and a link to an external stylesheet (styles.css) for styling the page. In the <body> section, there is a <header> element (currently empty), followed by a <nav> element containing an unordered list (<ul>) with three links to "Home," "About," and "Menu." Below the navigation bar, a <main> section includes an <h1> heading that reads "Learn a little about us!" followed by a <p> paragraph of placeholder text (lorem ipsum). After this, there is a secondary heading (<h2>) for "Contact Us" but no further content within that section. The page structure ends with a placeholder <footer>. On the right side, the webpage preview displays the "Home," "About," and "Menu" links in a horizontal navigation bar with a yellow background. The main section of the page has the "Learn a little about us!" heading and the accompanying lorem ipsum text in black font. Beneath the paragraph, the "Contact Us" section is also visible, but with no additional content. The layout is clean and simple, with the focus on the main heading and text about the bakery.

7. Below the <h2> tag, add the <form> tag and give it the following attributes:

a. action="" (an empty set of quotes)
b. method="post"
c. id="contactusform"

8. Within the <form> element, you will create four <label> elements. You will use these to create the following field labels:

a. “First Name:”
b. “Last Name:”
c. “Phone:”
d. “Email:”

9. Within each label and after the label text, you will be adding the following <input> tags, one input tag per label:

a. <input type="text" name="fname">
b. <input type="text" name="lname">
c. <input type="tel" name="phone">
d. <input type="email" name="email">

This is the expected output:

The image displays a split view with HTML code on the left and a webpage preview on the right. In the HTML code, the page continues from the previous layout, starting with a <form> element under the "Contact Us" heading. The form is set to submit data using the POST method with an ID of "contactusform." Within the form, there are several labeled input fields: one for "First Name" with a name attribute of fname, another for "Last Name" with a required name attribute of lname, a phone number field with type="tel" and name="phone", and an email input field with name="email". The form structure is neatly organized with labels for each field. After the form, the page closes the <main> section and includes a placeholder <footer> at the bottom. On the right side, in the webpage preview, the navigation bar with "Home," "About," and "Menu" links is displayed in a horizontal row with a yellow background. The main content includes a heading that reads "Learn a little about us!" followed by a paragraph of placeholder text. Below this, the "Contact Us" section is visible, showing a form with fields for "First Name," "Last Name," "Phone," and "Email." Each field is labeled appropriately, and the form layout is clear and easy to follow. The overall design is clean, with a straightforward structure focused on the form.

10. As you probably noticed, the labels and input tags are all “inline” and behave like normal text regarding their positioning. Let’s fix this for now by adding a <br> tag after each of the four label elements. This will separate each label and field onto their own lines.

This is the expected output:


The image shows a split view with HTML code on the left and a webpage preview on the right. On the left side, the HTML code is for an "About Us" page, continuing from a previously established structure. The form under the "Contact Us" section has additional formatting to improve spacing. After each label and input field, there are <br> (line break) tags to space out the form fields vertically. The form includes fields for "First Name," "Last Name" (with a required attribute), "Phone," and "Email." The form is set to use the POST method with an ID of "contactusform." On the right side, the webpage preview reflects the HTML structure. The navigation bar at the top displays the "Home," "About," and "Menu" links with a yellow background. The main content section features the heading "Learn a little about us!" followed by a paragraph of placeholder text. Below this is the "Contact Us" form, where users can input their first name, last name, phone number, and email address. The form fields are neatly aligned, with proper spacing between the labels and input boxes, making the form clear and easy to use. The overall design remains simple, functional, and easy to navigate.

11. Let’s finish building the form by adding the “Submit” and “Reset” buttons. Below the last label and after the <br>, add two new <input> tags, giving the first the type attribute of “submit” and the value attribute of “Submit.” The second will be a type attribute of “reset” with the value attribute of “Clear.”

This is the expected output:

The image shows an HTML code editor on the left and a webpage preview on the right. On the left, the HTML code is structured to display a "Contact Us" form. The form includes labeled input fields for "First Name," "Last Name," "Phone," and "Email." The last name and email fields are required, and there are two buttons below the form: one for submitting the form ("Submit") and another for resetting it ("Clear"). The form uses a method of "post" for submitting the input values. Additionally, the heading above the form reads "Contact Us," and the overall structure is clear and organized. On the right side, the webpage reflects the HTML code. The navigation bar at the top displays the links "Home," "About," and "Menu" with a yellow background. Below that, there is a section with the heading "Learn a little about us!" followed by a block of placeholder text ("Lorem ipsum"). Below the text is the "Contact Us" form, which includes text fields for first name, last name, phone, and email. The "Submit" and "Clear" buttons are clearly displayed below the form, with a simple, user-friendly design. The webpage is structured neatly and efficiently, providing both informational content and a contact form for user interaction.

hint

When you click the “Submit” button, it will likely reload the page and may or may not show an error message. It also might not do anything depending on your browser. Do not worry; this is because our form is not pointing to a handler script on any server, and thus the form has nowhere to submit the data.

That’s it for now. We will add a new type of control to the web form in later tutorials.

reflect

These are the basics of creating a web form using only labels and input tags to create the fields. There are more control types still to cover, but this gives you the basics of constructing an HTML web form.

The Contact Us form is probably the most common form that people think of. However, keep in mind that forms are actually rather powerful and allow us to give the user the ability to send data to a server and receive some form of response, either on the same page or via another channel of communication such as email. Furthermore, the fact that we can use a form to trigger a script file on the web server allows us to perform any kind of computational operations as a result of the form submission.

watch

View the following video for more on using tables to display data on a page. You'll notice that the instructor is using a different text editor, however, you can still follow.


terms to know

Input Tag <input>
An HTML tag used to create a wide range of form controls based on the value given to its type attribute.

Value Attribute
An attribute of most form controls that gives a unique value to the field or the field’s possible options.

Placeholder Attribute
An HTML attribute of most form controls that provide a temporary demonstration of what data is being requested within a form, but disappears when the user starts typing in the field.


4. Other Control Types

In addition to the <input> control tag, there are a number of other tags used to create controls and imply organization.

The <button> tag is another option for including a custom button in your form. It works the same as the <input> button, but it uses a different tag and is more customizable. Buttons do not do anything by default as they have to be linked to some kind of action. This is often accomplished by pointing the “onclick” attribute of the button to a JavaScript function or giving it the “type” attribute with a value of “submit.”

The <select> tag is a container control used for creating either a dropdown menu or a listbox. Dropdown menus start small, but when clicked they expand to show the available options. This can help conserve valuable screenspace on smaller screens. By providing the <select> tag with a “size” attribute and giving it a number, the <select> will create a listbox, which is a scrolling box containing multiple options to choose from. The number provided to the size attribute determines how many lines of text tall the listbox is. By default, only one option in the listbox can be selected. However, by providing the attribute keyword “multiple,” the user can hold the Ctrl key down and select multiple options within the same listbox.

The <option> tag is used within the <select> container to create the options for the user to choose from. Just like the <li> items for ordered and unordered lists, the <option> elements create the items in the dropdown or listbox. Additionally, these tags require a “value” attribute to help the server script identify which option or options were chosen.

The <optgroup> tag is an optional structure that creates a grouping of options within a listbox or dropdown menu.

EXAMPLE

Visually, this creates a bold heading for each group of options.

To create the groups, you simply surround the related options elements with the <optgroup> tags and give the <optgroup> tag the “label” attribute and value.

The <textarea> tag creates a large textbox for multiple lines of text. Often, textarea is used for comment boxes as it provides a larger area for the user to compose their response. Note that while you can set an initial height and width for the textarea using the “rows” and “cols” attributes, respectively, textareas are resizable by the user.

The <fieldset> tag is used to create a box that surrounds a group of controls in the form. By surrounding a group of controls in the <fieldset> tags, a line is drawn just around those controls. Furthermore, a label can be added to the box by adding the <legend> element as the first child of the fieldset and giving it a value.

EXAMPLE


<fieldset>
	<legend>Personal Information:</legend>
	<label>First name:
	<input type="text" placeholder="John"></label>
	<label>Last name:
	<input type="text" placeholder="Doe"></label>
	<input type="submit" value="Submit"></label>
</fieldset>

This will render as follows:

The <datalist> tag is an alternative option for the <select> control element that allows users to either select from the predefined list of options or type in their own choice. The HTML for a datalist is constructed the same as a select list, but it requires an id attribute and value as it needs to be linked with an input field. The <input> tag uses the “list” attribute and the value of the list’s id. This way, the input field is able to add the datalist to the text field as a dropdown but also still act as a normal text field.

EXAMPLE

The result is a text field that also includes a dropdown button on the right end.


<input list="browsers" name="browser">
<datalist id="browsers">
	<option value="Internet Explorer">
	<option value="Firefox">
	<option value="Chrome">
	<option value="Opera">
	<option value="Safari">
</datalist>

The <output> tag is a special field that serves as a textbox placeholder for the results of some calculations. Calculations are completed using JavaScript, and the name of the <output> element is what the JavaScript code uses to insert the calculated value into the output field.

term to know

Attribute Keyword
An HTML attribute that only requires the keyword to be present and does not require a value to be assigned.


5. Validation

When collecting data from users, it is important to validate the information provided by the user. There is an old saying that illustrates the need for data validation: “Garbage in, garbage out.” Validation is the process of verifying that what the user entered into the control fields is what was expected by the form. By default, an HTML form will not be submitted unless all the fields’ values meet their validation requirements, ensuring that only valid correct data is captured from the user. Incorrect, incomplete, and invalid data is useless to an organization; thus, it is important to put validation requirements on web form fields.

There are generally three ways to provide validation requirements for a web form.

Method Description
The type attribute Each type value will provide its own default validation requirements. For example, an “email” input type will validate the format of the email provided, and a “number” input type will validate that only valid numbers are present in the field.
Validation attributes Most form controls possess HTML attributes for customizing validation requirements. For example, adding the attribute keyword “required” will make it a mandatory field.
JavaScript JavaScript can be called in place of submitting the form. The JavaScript can be written to examine the values in each field and test for the standard and custom validation requirements. If all fields are valid, JavaScript will call the form’s submit function. This is useful when you have a unique field type and need to create your own custom validation.

The type attribute itself will provide its own default validation requirement. For example, if the type is set to number, the form submission will be blocked if there is a non-numeric value in the field. Furthermore, depending on the control type, there will be HTML attributes that can be added to further customize the validation requirements. Number fields can be given a “min” and/or a “max” attribute to set the range of possible values. Text fields can be given “minlength” and “maxlength” to specify the limits of characters within the field . . . and more.

learn more

There are quite a few validation attributes that can be added to input fields and other form controls. You can find a list of attributes for the <input> tag, many of which are validation attributes: www.w3schools.com/tags/tag_input.asp.

To validate using JavaScript, the form’s regular submit button will be replaced with a generic button (either an <input> with the “button” type or an actual <button> element) with the button label “Submit.” Then, the button’s HTML attribute “onclick” will point to a JavaScript function that will check the existing validation requirements set by the field type and any validation attributed, as well as perform its own custom-defined validation checks as dictated by the developer. JavaScript validation will be discussed in more detail in a later unit.

A more advanced validation attribute that most form controls possess is called the pattern attribute, which accepts a regular expression value. Regular expression is a special type of syntax that is used to validate the specific format of a sequence of characters.

EXAMPLE

If you needed to validate a user’s email to ensure that it contains any number of valid email characters (0-9, a-z), an @ symbol, any number of additional valid characters (0-9, a-z), a period, and then a 2- to 4-character top domain, you would provide the <input> tag with the “regex” attribute and give it a value that is a regular expression like this:

<input type="text" pattern="[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}">

One final aspect of web form validation is that of security. You may recall that SQL injection is a type of attack wherein the attacker will place SQL commands in a form’s text field. If the form does not have any security checks in place, the SQL query will likely be executed by the database server, possibly exposing sensitive information. There are mechanisms within JavaScript that will prevent such attacks and will be discussed in a later unit.

Now that you have seen how to create additional types of form controls, it’s time to practice!

try it

Directions: In this activity, you will edit the “Contact Us” web form to include additional control types, including the dropdown menu with option groups, textarea, and a fieldset organizer. Additionally, we will add some validation to the fields.

1. Return to your project, your insertion point between the last <br> in the form and before the first button. Add a label with the text “Reason for communication:” and add a <select> element, giving the name attribute a value of “commenttype.” This will be used to indicate what kind of communication this will be: “feedback” in the form of a “Complaint,” “Compliment,” or “Comment” or a “request” in the form of a “Catering” or “Suggestion.” We will use <optgroups></no wiki> for the two groups (feedback and request) and the <option> elements for the choices.


<label>Reason for communication:
       <select name="commenttype">
              <optgroup label="Feedback">
                     <option value="comment">Comment</option>
                     <option value="compliment">Compliment</option>
                     <option value="complaint">Complaint</option>
              </optgroup>
              <optgroup label="Request">
                     <option value="catering">Catering</option>
                     <option value="suggestion">Suggestion</option>
              </optgroup>
       </select>
</label><br>

This is the expected output:

The image shows a split view with HTML code on the left and a webpage preview on the right. On the left, the HTML code builds a contact form that now includes a dropdown menu for selecting the "Reason for communication." The form contains labeled input fields for "First Name," "Last Name," "Phone," and "Email," with required attributes on the last name and email fields. Following the email input is a label and a dropdown selection box (<select>) with two option groups: "Feedback" and "Request." The "Feedback" group includes options for "Comment," "Compliment," and "Complaint," while the "Request" group includes options for "Catering" and "Suggestion." Below the dropdown, there are two buttons: one for submitting the form (Submit) and one for resetting the form (Clear). On the right side, the webpage preview mirrors the HTML structure. The navigation bar at the top displays "Home," "About," and "Menu" links with a yellow background. Below that, the main content displays the "Learn a little about us!" heading followed by a paragraph of placeholder text. The contact form is displayed with labeled fields for "First Name," "Last Name," "Phone," and "Email," and a dropdown for selecting a reason for communication. The dropdown menu is expanded, showing the options under the "Feedback" and "Request" categories, with "Complaint" currently highlighted. Below the dropdown, the "Submit" and "Clear" buttons are shown, ready to be used. The overall design of the page is clean, organized, and user-friendly.

2. Next, provide the user with an area to write their feedback or request. This will need to be something larger than a text field as the user needs to be able to easily review and edit what they wrote. Create a label for “Comments:” and within it add a <textarea> element (remember, textareas are not self-closing). Give the textarea a name attribute of “comment.” Add a <br> after the label text and after the end of the label.

Additionally, set the textarea’s cols attribute to 7 and the rows attribute to 30.

This is the expected output:

In the image, the HTML code on the left creates a "Contact Us" form, which is reflected on the webpage preview on the right. On the left, the form includes labeled input fields for first name, last name, phone number, and email. Below these fields, there is a dropdown menu labeled "Reason for communication" with options such as "Comment," "Compliment," "Complaint," "Catering," and "Suggestion." Following that, there is a "Comments" section where users can input text in a larger text area. Finally, the form has two buttons: "Submit" to send the form data and "Clear" to reset the input fields. On the right, the webpage displays the form, starting with a navigation bar at the top with links for "Home," "About," and "Menu" on a yellow background. Below the navigation bar is the heading "Learn a little about us!" followed by placeholder text. The contact form appears beneath that, with fields for user input such as name, phone, email, the reason for communication, and a comment section. The form is structured clearly, with enough space for user input, making it functional and user-friendly.

3. Next, practice using the <fieldset> element to surround the first four fields, and give it a <legend> of “Personal Information.” Surround the first four fields, including their labels, with the <fieldset> element. Next, just after the opening tag of the fieldset, add a <legend> element and add the following within the tags: “Personal Information:”

This is the expected output:

The image shows an updated "Contact Us" form in HTML on the left, and its corresponding rendered output on the right. In the HTML code, a <fieldset> element is used to group related fields within the form, and a <legend> element is added to give a label to this grouping. The <legend> reads "Personal Information," which is applied to the input fields for First Name, Last Name, Phone, and Email. Each field has been labeled and includes a line break (<br>) after it to ensure proper spacing. Additionally, the Last Name and Email fields are marked as required. On the right side, the form is displayed on the webpage. The navigation bar remains at the top, followed by a section encouraging visitors to "Learn a little about us." The form itself includes a clearly defined section for "Personal Information," with appropriately spaced input fields for entering first name, last name, phone number, and email. Below this, a dropdown menu labeled "Reason for communication" allows users to select a reason, such as comment, compliment, complaint, catering, or suggestion. A text area for comments and submit/clear buttons are positioned at the bottom. This form is now better organized visually with the <fieldset> and <legend> providing clear structure and grouping for the personal information fields, improving readability and user experience.

4. The last part of this activity will be to add form validation attributes. You will make certain fields required by adding the required keyword attribute to the <input> tags. You will also add a new <input> field with the “number” type, which will ask the user how many days a week they visited the establishment and you will set a minimum value of 0 and a maximum value of 7.

Below the <br> just after the <fieldset> that you just created, add a new <label> with the text “How many days per week do you visit the shop?” and an <input> tag with the “number” type and a name of “frequency.” Lastly, add the “min” attribute and give it a value of 0, and add the “max” attribute and give it a value of 7. This will limit the possible values to only 0 through 7. Don’t forget the trailing <br>.

This is the expected output:

The image shows an updated version of the "Contact Us" form with an additional question asking, "How many days per week do you visit the shop?" The code uses an <input> element of type "number" with a minimum value of 0 and a maximum value of 7 to collect this data. This question is presented between the personal information section and the reason for communication dropdown. The form structure continues to be well-organized, with each section clearly labeled and spaced appropriately. On the right, the form rendered on the webpage includes the new input field for the number of visits per week, providing a small box for numerical input directly under the "Personal Information" section. This additional input fits well into the form structure, maintaining the clear and user-friendly layout. The "Reason for communication" dropdown and the "Comments" section remain at the bottom, followed by the Submit and Clear buttons. This small enhancement allows users to provide more specific feedback about their frequency of visits, improving the depth of information collected through the form.

5. The final step is to make certain fields required by adding the required keyword attribute. Make the last name, email, frequency, and comments fields required. Remember to add the “required” keyword to the tag that actually creates the control, not the label.

You should not be able to successfully submit the form without satisfying the validation requirements. If you click “Submit,” validation will block the submission and will show error messages pointing to the problem within the form.

This is the expected output:

The image displays an HTML form on the right, showing validation in action. The field for email has triggered a browser-provided alert, indicating that it is a required field and must be filled out before the form can be submitted. The rest of the form remains unchanged, but the validation ensures that the required fields—such as "First Name," "Last Name," "Phone," "Email," and "Comments"—must be completed before the form can be processed. In the HTML code on the left, each required field has the required attribute, enforcing this client-side validation. The browser automatically checks for any missing inputs in these fields and provides a tooltip-like message to prompt the user to fill them out. This form uses a clear structure with validation to ensure data completeness, which helps ensure that users provide all necessary information before submission. The form fields remain well-labeled and easy to interact with, keeping the overall design user-friendly.

6. If you haven't already done so, now is a good time to save your project.

reflect

While there are a variety of additional form controls beyond what you have seen, you have successfully practiced creating the most common control types that you will likely use in your future. Furthermore, you also practiced adding some basic validation requirements to the form to ensure that every form submission contains valid, usable data for the recipient.

make the connection
In Touchstone Task 2.1: Creating HTML Pages, you will need to create a web form for client feedback and custom order creation on the about us/contact page.

terms to know

Validation
The process of verifying that each value entered into each field meets the specified requirements.

Validation Attributes
HTML attributes for form controls that add validation requirements for the data entered into the field.

Pattern Attribute
An HTML attribute for form controls that use “regular expression” statements to validate the format and completeness of the value entered into a field.

Regular Expression
A sequence of characters that specifies a pattern to compare against, used for format text validation.

Required Keyword Attribute
An HTML attribute keyword that places a validation requirement requiring that the user enter some value or make a selection within a particular form control.

summary
In this lesson, you learned about web forms and the aspects of the form tag used for creating web forms. You also learned about form controls, starting with the input tag and then learned about other form control tag types. Lastly, you were introduced to form validation and the three mechanisms for creating validation requirements.

Source: This Tutorial has been adapted from "The Missing Link: An Introduction to Web Development and Programming " by Michael Mendez. Access for free at https://open.umn.edu/opentextbooks/textbooks/the-missing-link-an-introduction-to-web-development-and-programming. License: Creative Commons attribution: CC BY-NC-SA

Terms to Know
Action Attribute

The HTML attribute of a <form> tag that specifies what server-side script will receive and handle the form submission.

Attribute Keyword

An HTML attribute that only requires the keyword to be present and does not require a value to be assigned.

Form Controls

Elements such as checkboxes, radio buttons, and menus, which allow users to enter, select, or edit information; perform actions; or display data.

Input Tag <input>

An HTML tag used to create a wide range of form controls based on the value given to its type attribute.

Method Attribute

The HTML attribute for a <form> tag that specifies what HTTP method to use when transmitting the form data.

Pattern Attribute

An HTML attribute for form controls that use “regular expression” statements to validate the format and completeness of the value entered into a field.

Payload

The portion of a network packet that contains the actual data being transmitted and is encapsulated in the packet’s header and trailer.

Placeholder Attribute

An HTML attribute of most form controls that provide a temporary demonstration of what data is being requested within a form, but disappears when the user starts typing in the field.

Regular Expression

A sequence of characters that specifies a pattern to compare against, used for format text validation.

Required Keyword Attribute

An HTML attribute keyword that places a validation requirement requiring that the user enter some value or make a selection within a particular form control.

Validation

The process of verifying that each value entered into each field meets specified requirements.

Validation Attributes

HTML attributes for form controls that add validation requirements for the data entered into the field.

Value Attribute

An attribute of most form controls that give a unique value to the field or the field’s possible options.

Web Form

A document that provides users with an interface of fields for typing in text or numeric data or choosing from a list of options.