Mastering HTML Forms: A Comprehensive Guide with Examples and Resources

Atlas Anomalous
18 min readFeb 12, 2023

--

Introduction to HTML Forms

HTML forms are an essential part of web development, and play a critical role in collecting and transmitting information from users to a server. Whether you’re building a simple contact form, an online store checkout, or a complex survey, HTML forms are the backbone of these interactions.

In this article, we’ll provide a comprehensive introduction to HTML forms, including:

  • What HTML forms are and how they work
  • The different types of form controls, including text fields, checkboxes, radio buttons, and more
  • How to use HTML attributes to configure and customize form controls
  • Techniques for input validation, such as required fields and pattern matching
  • Advanced form techniques, such as AJAX submissions and server-side processing

By the end of this article, you’ll have a solid understanding of HTML forms and be able to build effective and user-friendly forms for your web applications.

HTML Forms MidJourney AI

Creating a Basic HTML Form

Now that we’ve covered the basics of HTML forms, let’s dive into creating our first form. To create a form, we’ll use the <form> element, which acts as a container for our form controls.

Here’s an example of a basic HTML form:

<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<input type="submit" value="Submit">
</form>

Let’s break down this example step by step:

  1. The <form> element acts as the container for our form controls.
  2. The <label> element is used to provide a text description for each form control. The for attribute specifies which form control the label is associated with, and the text between the label tags is the description.
  3. The <input> element is used to create a text field. The type attribute specifies the type of input control, in this case “text” for a single-line text field or “email” for an email address field. The id attribute is used to uniquely identify the form control, and the name attribute is used to identify the form control on the server when the form is submitted.
  4. The <textarea> element is used to create a multi-line text field. Like the <input> element, the id and name attributes are used to identify the form control.
  5. The <input type=”submit”> element is used to submit the form. The value attribute is used to specify the text that appears on the submit button.

Note that the form controls in this example are basic and don’t include any form attributes for configuring or customizing the controls. We’ll cover form attributes and input validation in the next sections of this article.

Try copying and pasting the code into an HTML file and opening it in your browser to see the form in action. While the form looks functional, it doesn’t actually do anything yet. To make the form functional, we need to specify a server-side script to process the form data. This is beyond the scope of this article, but there are many resources available online to learn more about server-side scripting and form processing.

Front-End Engineers Hard @ Work MidJourney AI

Form Controls

In the previous section, we covered the basics of creating a simple HTML form. In this section, we’ll explore the different types of form controls available and how to use them.

Here’s a list of the most common form controls and their corresponding HTML elements:

  1. Text field: <input type=”text”>
  2. Email field: <input type=”email”>
  3. Password field: <input type=”password”>
  4. Radio button: <input type=”radio”>
  5. Checkbox: <input type=”checkbox”>
  6. Drop-down list: <select> and <option>
  7. Submit button: <input type=”submit”>

Let’s explore each form control in more detail.

Text field

The text field is the most basic form control and is used to accept single-line text input from the user. To create a text field, use the <input type=”text”> element:

<label for="name">Name:</label>
<input type="text" id="name" name="name">

Email field

The email field is similar to the text field, but is specifically designed for entering email addresses. To create an email field, use the <input type=”email”> element:

<label for="email">Email:</label>
<input type="email" id="email" name="email">

Password field

The password field is used to accept confidential text input, such as a password. The text entered into the password field is masked with asterisks or dots to protect the user’s privacy. To create a password field, use the <input type=”password”> element:

<label for="password">Password:</label>
<input type="password" id="password" name="password">

Radio button

Radio buttons are used to present a set of mutually exclusive options to the user, from which only one option can be selected. To create a set of radio buttons, use the <input type=”radio”> element:

<label for="gender-male">Male</label>
<input type="radio" id="gender-male" name="gender" value="male">
<label for="gender-female">Female</label>
<input type="radio" id="gender-female" name="gender" value="female">

Note that the name attribute is used to group the radio buttons together, so that only one option can be selected. The value attribute is used to specify the value that will be transmitted to the server when the form is submitted.

Checkbox

Checkboxes are used to present a set of options to the user, from which one or more options can be selected. To create a checkbox, use the <input type=”checkbox”> element:

<label for="newsletter">Subscribe to our newsletter</label>
<input type="checkbox" id="newsletter" name="newsletter">

Drop-down list

The drop-down list is used to present a list of options to the user, from which only one option can be selected. To create a drop-down list, use the <select> and <option> elements:

<label for="language">Preferred language:</label>
<select id="language" name="language">
<option value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
</select>

Submit button

The submit button is used to submit the form to the server for processing. To create a submit button, use the <input type=”submit”> element:

<input type="submit" value="Submit">

The value attribute is used to specify the text that will be displayed on the submit button.

And that’s it! With these form controls, you can create a wide range of forms to collect user data. Of course, there are many other form controls available, such as file inputs, hidden inputs, and more, but these are the most common.

Forms are a crucial aspect of web development, and are used to collect data from users. With the form controls covered in this article, you now have the tools to create a wide range of forms to meet your needs.

HTML Forms MidJourney AI

Form Attributes

HTML forms have various attributes that can be used to customize their behavior and appearance. In this section, we’ll cover the most commonly used form attributes.

Action Attribute

The action attribute is used to specify the URL of the server-side script that will process the form data. The form data is sent to the server when the user submits the form.

<form action="https://www.example.com/form-handler.php" method="post">

Method Attribute

The method attribute is used to specify the HTTP method that will be used to submit the form data. The two most common methods are GET and POST. The GET method is used to retrieve data, while the POST method is used to submit data.

<form action="https://www.example.com/form-handler.php" method="post">

Encoding Type Attribute

The enctype attribute is used to specify the encoding type of the form data. The most commonly used encoding type is application/x-www-form-urlencoded, which is used to encode the form data as name-value pairs.

<form action="https://www.example.com/form-handler.php" method="post" enctype="application/x-www-form-urlencoded">

Autocomplete Attribute

The autocomplete attribute is used to specify whether the browser should automatically complete form fields for the user. The default value is on, which means that the browser will try to automatically complete form fields. The off value can be used to turn off autocompletion.

<input type="text" name="username" autocomplete="off">

Placeholder Attribute

The placeholder attribute is used to specify a short hint that describes the expected value of a form field. The hint is displayed in the form field when it is empty, and disappears when the user starts typing.

<input type="text" name="username" placeholder="Enter your username">

Required Attribute

The required attribute is used to specify that a form field must be filled in before the form can be submitted. If the form field is left empty, the browser will display an error message and prevent the form from being submitted.

<input type="text" name="username" required>

These are some of the most commonly used form attributes in HTML. By using these attributes, you can customize the behavior and appearance of your HTML forms to meet your specific needs.

Forms are a crucial aspect of web development, and the use of form attributes can make a big difference in the user experience. Whether you’re a seasoned web developer or just getting started, be sure to make use of these attributes in your HTML forms.

Optics from the Inside MidJourney AI

Input Validation: The Importance of Ensuring Data Accuracy

When it comes to web development, forms play a critical role in collecting and transmitting information from users to websites. While forms offer great convenience and ease of use, they also pose a security risk if not properly validated. Input validation is a process of checking the data entered into a form by the user for accuracy, completeness, and compliance with specified data types, formats, and other constraints. The main goal of input validation is to prevent malicious or incorrect data from being submitted and processed.

In this section, we’ll explore the different techniques for input validation in HTML forms, and show you how to implement them using code examples.

HTML5 Form Validation Attributes

HTML5 introduced several new attributes for form validation, which make it easier for developers to implement basic validation without writing any JavaScript code. These attributes include:

  • required: Specifies that an input field must be filled out before the form can be submitted. Example:
<input type="text" name="username" required>
  • pattern: Specifies a regular expression pattern that the input value must match. Example:
<input type="text" name="email" pattern="[a-z0–9._%+-]+@[a-z0–9.-]+\.[a-z]{2,}$">
  • minlength: Specifies the minimum number of characters required for an input field. Example:
<input type="text" name="password" minlength="8">
  • maxlength: Specifies the maximum number of characters allowed for an input field. Example:
<input type="text" name="zipcode" maxlength="5">
  • min: Specifies the minimum value for an input field of type “number”. Example:
<input type="number" name="age" min="18">
  • max: Specifies the maximum value for an input field of type “number”. Example:
<input type="number" name="rating" max="5">

JavaScript Form Validation

While HTML5 form validation attributes provide a basic level of validation, they may not be enough for more complex validation requirements. In such cases, you can use JavaScript to perform input validation.

One common approach is to use a JavaScript function that checks the values of form inputs before they are submitted. For example:

<form onsubmit="return validateForm()">
<input type="text" name="username" id="username">
<input type="email" name="email" id="email">
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
if (username == "") {
alert("Username is required");
return false;
}
if (email == "") {
alert("Email is required");
return false;
}
return true;
}
</script>

In this example, the validateForm() function checks if the values of the username and email inputs are empty, and displays an error message if they are. The form will only be submitted if the function returns.

Photo by Tai Bui on Unsplash

Advanced Form Techniques

Advanced form techniques involve taking HTML forms to the next level, incorporating features such as custom error messages, styling, and dynamic interaction.

Here are some of the key advanced form techniques you can use to enhance the functionality and usability of your forms:

1. Custom Error Messages: HTML5’s built-in form validation attributes provide basic error messages, but you can customize these messages to fit the specific needs of your form. This can be done by using JavaScript to manipulate the error messages displayed.

Here’s an example of a custom error message in code:

<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<span id="emailError" style="display:none; color:red;">
Please enter a valid email address.
</span>
<br><br>
<button type="submit">Submit</button>
</form>
<script>
const emailInput = document.querySelector('#email');
const emailError = document.querySelector('#emailError');
emailInput.addEventListener('input', function() {
if (!emailInput.validity.valid) {
emailError.style.display = 'block';
} else {
emailError.style.display = 'none';
}
});
</script>

2. Styling: HTML forms are often seen as dull and unappealing, but with the help of CSS, you can easily style your forms to match the look and feel of your website. This includes customizing the layout, colors, and fonts of your form elements.

Here’s an example of form styling using CSS:

<!DOCTYPE html>
<html>
<head>
<style>
/* Add styling to the form */
form {
width: 500px;
margin: 0 auto;
padding: 20px;
background-color: #f2f2f2;
border-radius: 10px;
}

/* Add styling to the form elements */
form label {
font-weight: bold;
margin-bottom: 10px;
display: block;
}

form input[type="text"], form input[type="email"], form textarea {
width: 100%;
padding: 10px;
margin-bottom: 20px;
border-radius: 5px;
border: none;
}

form input[type="submit"] {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}

form input[type="submit"]:hover {
background-color: #3e8e41;
}
</style>
</head>
<body>
<form>
<label>Name:</label>
<input type="text" name="name" required>
<label>Email:</label>
<input type="email" name="email" required>
<label>Message:</label>
<textarea name="message" rows="5" required></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>

This is just one example of how you can style a form using CSS. You can use different CSS properties to change the appearance of your form and make it look the way you want.

3. Dynamic Interaction: HTML forms can be made dynamic by using JavaScript to manipulate the form’s behavior. For example, you can use JavaScript to show and hide form fields based on user input or to dynamically update form fields with data from an external source.

Here’s an example of dynamic interaction using JavaScript:

<!DOCTYPE html>
<html>
<head>
<script>
// Function to validate form input
function validateForm() {
// Get input values
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var message = document.forms["myForm"]["message"].value;
// Check if inputs are not empty
if (name == "" || email == "" || message == "") {
alert("All fields are required");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
<label>Name:</label>
<input type="text" name="name" required>
<label>Email:</label>
<input type="email" name="email" required>
<label>Message:</label>
<textarea name="message" rows="5" required></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>

In this example, we created a JavaScript function validateForm() to validate the form inputs. The function checks if the inputs for name, email, and message are not empty. If any of the inputs are empty, an error message will be displayed. The form will only be submitted if all inputs are filled. The JavaScript function is called when the form is submitted using the onsubmit attribute.

This is just one example of how you can add dynamic interaction to your HTML form using JavaScript. You can add more complex logic or use other JavaScript functions to create more advanced interactions.

4. AJAX Form Submission: AJAX (Asynchronous JavaScript and XML) is a technology that allows you to submit form data without reloading the page. This can provide a faster and smoother user experience, as well as reduce the amount of data transmitted over the network.

Here’s an example of AJAX form submission using jQuery:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#myForm").submit(function(event) {
event.preventDefault();
var formData = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "submit-form.php",
data: formData,
success: function(data) {
$("#form-response").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="myForm">
<label>Name:</label>
<input type="text" name="name" required>
<label>Email:</label>
<input type="email" name="email" required>
<label>Message:</label>
<textarea name="message" rows="5" required></textarea>
<input type="submit" value="Submit">
</form>
<div id="form-response"></div>
</body>
</html>

In this example, we included the jQuery library in the head section of the HTML file. In the script, we used the $(document).ready() function to wait until the document is ready before attaching the event listener to the form. The event listener is attached to the form using the submit event of the form.

When the form is submitted, the event.preventDefault() function is called to prevent the default behavior of the form submit. The form data is collected using the serialize() function and stored in a variable formData.

Next, we use the $.ajax() function to send the form data to a PHP script named submit-form.php using a POST request. If the request is successful, the success function will be called, and the response from the server will be displayed in the div with the id of form-response.

This is just one example of how you can use AJAX to submit a form in HTML. You can customize the AJAX request based on your needs and the requirements of your application.

5. Server-side Validation: While client-side validation (using HTML5 or JavaScript) is useful, it’s important to also perform validation on the server-side. This provides an extra layer of security, as it ensures that data is validated even if the client-side validation is bypassed.

Server-side validation is an important part of form processing, as it helps ensure that the data entered by the user is valid and can be safely processed by the server. In this section, we’ll take a look at an example of server-side validation using PHP.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get the form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Check for errors
$errors = array();
if (empty($name)) {
$errors[] = "Name is required";
}
if (empty($email)) {
$errors[] = "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
if (empty($message)) {
$errors[] = "Message is required";
}
// If there are no errors, send the email
if (empty($errors)) {
$to = "you@example.com";
$subject = "New message from $name";
$body = "Name: $name\n\nEmail: $email\n\nMessage:\n$message";
mail($to, $subject, $body);
// Redirect to the success page
header("Location: success.php");
exit;
}
}
?>

In this example, we’re using the $_SERVER superglobal to check if the form has been submitted. If it has, we get the form data and store it in variables. Next, we check for errors. In this case, we’re checking that the name, email, and message fields are not empty, and that the email is in a valid format. If there are no errors, we use the mail() function to send an email to a specified recipient. Finally, we redirect the user to a success page.

It’s important to note that this is just one example of server-side validation, and there are many other ways to accomplish this. Additionally, this example does not include any security measures to prevent against malicious attacks, such as SQL injection or cross-site scripting (XSS). Be sure to properly sanitize and validate user input before processing it on the server.

Incorporating these advanced form techniques can greatly improve the functionality and user experience of your forms. By taking the time to implement these techniques, you’ll be able to create forms that are not only effective, but also visually appealing and engaging for users.

Photo by Thao LEE on Unsplash

Server-side Processing

Server-side processing refers to the process of handling form data on the server, rather than the client-side. This is an important aspect of web development as it helps to ensure the security and reliability of the data being submitted through the form. In this section, we’ll cover the basics of server-side processing and show you how to implement it using PHP.

Example of Server-side Validation in PHP

Let’s start by creating a basic HTML form that we can use for this example. The following code creates a form with three fields: name, email, and message.

<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea><br><br>
<input type="submit" value="Submit">
</form>

Once we have our HTML form set up, we can start adding server-side validation to ensure that the data entered by the user is valid. The following PHP code shows how to validate the name, email, and message fields:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
if (empty($name)) {
$error_message = "Name is required";
} elseif (empty($email)) {
$error_message = "Email is required";
} elseif (empty($message)) {
$error_message = "Message is required";
} else {
$success_message = "Form submitted successfully!";
}
}
?>

In this example, we’re using the $_SERVER[“REQUEST_METHOD”] variable to check if the form has been submitted. If the form has been submitted, we retrieve the values of the name, email, and message fields using the $_POST array. Then, we use a series of if-else statements to check if any of the fields are empty. If any of the fields are empty, we set an error message. If all of the fields have been filled in, we set a success message.

Of course, this is just a basic example of server-side validation in PHP. You can expand on this to include more advanced validation techniques, such as checking the format of the email address or limiting the number of characters in the message field.

Server-side processing is an important aspect of web development that helps to ensure the security and reliability of the data being submitted through your form. By using server-side validation, you can ensure that the data entered by the user is valid before it’s processed and stored on the server.

We hope that this article has been helpful in giving you a better understanding of server-side processing and how to implement it in PHP. If you have any questions or comments, feel free to leave them in the comments section below. And don’t forget to check out GM Cube Designs for more great web development resources!

Photo by Taylor Vick on Unsplash

Online Resources

There are many great online resources for learning about HTML forms, including tutorials, articles, videos, and interactive exercises. Here are some of the best places to start:

  1. W3Schools: This is one of the most comprehensive resources for web development and includes a wide range of tutorials and examples for HTML forms.
  2. Codecademy: Codecademy offers interactive lessons and projects on a variety of topics, including HTML forms. They have an intuitive platform that is great for beginners.
  3. Udemy: Udemy is a massive online learning platform that offers courses on HTML forms and web development in general. You can find a wide range of courses, from beginner-friendly to advanced, with new ones being added regularly.
  4. YouTube: YouTube is a great resource for learning HTML forms, with a wide range of tutorials and step-by-step guides available. You can find videos on specific topics, such as input validation, or follow a comprehensive course from start to finish.
  5. Mozilla Developer Network: MDN is a comprehensive resource for web developers, with articles, tutorials, and interactive examples on a wide range of topics, including HTML forms.
  6. GitHub: GitHub is a great resource for finding open-source projects related to HTML forms. You can browse code, see how others have approached problems, and contribute your own solutions.
  7. FreeCodeCamp — a non-profit organization that offers a full curriculum of web development courses, including HTML, CSS, and JavaScript.
  8. Khan Academy — a non-profit organization that offers a variety of educational resources, including a computer programming curriculum that covers HTML and CSS.

With these resources, you will be able to deepen your understanding of HTML forms and apply this knowledge to your own projects. And if you need more help or inspiration, be sure to check out GM Cube Designs! We offer a wide range of web development services, including custom forms and custom form functionality. So why not reach out to us today and see what we can do for you?

Photo by Uriel SC on Unsplash

Source Books

There are many great books available to help you learn about HTML forms. Here are some of the best:

  1. HTML & CSS: Design and Build Websites by Jon Duckett: This is a comprehensive guide to HTML and CSS that covers everything from the basics to more advanced topics, including HTML forms. The book has a clear and accessible style, with plenty of examples and visual aids.
  2. HTML5 & CSS3 for the Real World by Alexis Goldstein, Louis Lazaris, and Estelle Weyl: This is a practical guide to HTML5 and CSS3 that covers a wide range of topics, including HTML forms. The book is written for intermediate to advanced web developers and includes best practices, tips, and techniques for building responsive websites.
  3. Forms that Work: Designing Web Forms for Usability by Caroline Jarrett, Gerry Gaffney and Steve Krug: This book is a comprehensive guide to designing usable web forms. It covers everything from the basics of form design to advanced topics such as accessibility, error handling, and progressive enhancement.
  4. Pro HTML5 and CSS3 Design Patterns by Michael Bowers, Dionysios Synodinos and Victor Sumner: This book is a comprehensive guide to HTML5 and CSS3 design patterns, including those used in HTML forms. The book covers a wide range of topics, including responsive design, CSS animations, and accessibility.
  5. HTML, CSS & JavaScript Web Publishing in One Hour a Day, Sams Teach Yourself (7th Edition) by Laura Lemay, Rafe Colburn, and Jennifer Kyrnin: This is a beginner-friendly guide to HTML, CSS, and JavaScript that covers everything from the basics to more advanced topics, including HTML forms. The book is written in a clear and accessible style, with plenty of examples and exercises.

Whether you’re a beginner or an advanced web developer, there is a book out there to help you learn about HTML forms. So why not start reading today and take your skills to the next level?

Photo by Jez Timms on Unsplash

Conclusion

HTML forms are an essential aspect of web development, allowing users to input and send data to a server. From basic forms to more advanced techniques like dynamic interaction, AJAX submissions, and server-side processing, understanding how to create and work with HTML forms is a crucial skill for any web developer.

In this article, we covered the key concepts of HTML forms, including form controls, attributes, input validation, form styling, advanced techniques and server-side processing. We also provided examples in code to help you see how these concepts are applied in practice.

At GM Cube Designs, we specialize in creating high-quality, custom web development solutions, including form design and implementation. If you’re interested in learning more about how we can help you with your web development needs, be sure to check us out.

We hope this article has been informative and helpful in your journey to learn about HTML forms. If you found it useful, be sure to like, comment, and follow us on Medium for more great articles on web development and other related topics.

HTML Secrets MidJourney AI

--

--

Atlas Anomalous

Full-Stack Dev & Founder @GMCubeDesigns. Building impactful digital solutions. Pushing boundaries in web development. Delivering top-notch projects.