go backBack to blog

Forms and Validations in HTML

Published on Jan 22 2023

Last updated on May 04 2023

Photo by Esther Jiao on Unsplash
No translation available.
Add translation

HTML forms and form validation are essential parts of modern web development. In this blog post, we will explore the key concepts and best practices for developing HTML forms with effective validation.

HTML Forms

HTML forms allow users to input data and interact with web applications. Forms can be used for a wide variety of purposes, from simple contact forms to complex data collection and submission workflows. In HTML, forms are created using the <form> element, which has several attributes that control its behavior. Here is an example of a basic HTML form:

forms.html

<form action="/submit-form" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>

In this example, we have created a simple form that collects the user's name and email address. When the user clicks the "Submit" button, the form data will be sent to the URL "/submit-form" using the HTTP POST method.

Form Validation

Form validation is the process of checking user input data to ensure that it meets specific requirements, such as being in the correct format or within a certain range. There are two types of form validation: client-side validation and server-side validation.

Client-Side Validation

Client-side validation is performed on the user's device using JavaScript, before the form is submitted. This type of validation provides instant feedback to the user and can help prevent unnecessary server requests. Client-side validation is especially important for web applications that require a high degree of interactivity or real-time feedback. Here is an example of client-side form validation:

form-client-side-validation.html

<form action="/submit-form" method="POST" onsubmit="return validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (name == "" || email == "") {
alert("Please fill out all required fields");
return false;
}
return true;
}
</script>

In this example, we have added the required attribute to the name and email input fields, which will prevent the form from being submitted if they are empty. We have also added an onsubmit attribute to the form, which calls the validateForm() function. This function checks if the name and email fields are empty and displays an alert if they are.

Server-Side Validation

Server-side validation is performed on the server after the form has been submitted. This type of validation is essential for security and can catch any validation errors that may have been missed by the client-side validation. Server-side validation is especially important for web applications that handle sensitive data or perform critical operations. Here is an example of server-side form validation using PHP:

form-server-side-validation

$name = $_POST["name"];
$email = $_POST["email"];
if (empty($name) || empty($email)) {
echo "Please fill out all required fields";
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Please enter a valid email address";
exit;
}
// Process the form data

In this example, we have assumed that the form data is being submitted using the HTTP POST method. The $_POST superglobal variable is used to retrieve the values of the name and email fields. The empty() function is used to check if the fields are empty, and the filter_var() function is used to check if the email address is valid. If any validation errors are detected, an error message is echoed to the user, and the script exits. Otherwise, the form data is processed.

Common Validation Techniques

There are several common validation techniques that can be used to ensure the accuracy and completeness of user input data. Here are some of the most widely used validation techniques:

Required Fields

Required fields are input fields that must be filled out before a form can be submitted. Required fields are indicated by adding the required attribute to the input element. For example:

validationTechniques-requiredFields.html

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

Email Validation

Email validation is the process of ensuring that an email address is valid and correctly formatted. Email validation can be performed using regular expressions or built-in browser validation. Here is an example of email validation using regular expressions:

validationTechniques-emailValidations.js

function validateEmail(email) {
var re = /\S+@\S+\.\S+/;
return re.test(email);
}

This function takes an email address as input and returns true if it is valid and false if it is not.

Password Strength

Password strength is a measure of how difficult it is for an attacker to guess or brute-force a password. Password strength can be enforced by requiring users to use a combination of uppercase and lowercase letters, numbers, and symbols, and by setting minimum and maximum length requirements. Here is an example of password strength validation using regular expressions:

validationTechniques-passwordStrength.js

function validatePassword(password) {
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/;
return re.test(password);
}

This function takes a password as input and returns true if it meets the specified requirements and false if it does not.

Conclusion

In conclusion, HTML forms and form validation are essential components of web development. HTML provides a simple and intuitive way to create forms, while client-side and server-side validation can help ensure that user input data is valid and secure. By understanding these key concepts and using them effectively, web developers can create robust and user-friendly web applications. Common validation techniques such as required fields, email validation, and password strength can help ensure that user input data is accurate and complete.

Tags:
front-end
html
security
My portrait picture

Written by Alissa Nguyen

Alissa Nguyen is a software engineer with main focus is on building better software with latest technologies and frameworks such as Remix, React, and TailwindCSS. She is currently working on some side projects, exploring her hobbies, and living with her two kitties.

Learn more about me


If you found this article helpful.

You will love these ones as well.

  • Photo by NASA
    Apr 06 2022 — 5 min readWeb Development Explained: How the Web Works
    #hosting#html
  • Photo by Sunira Moses on Unsplash
    Jan 22 2023 — 5 min readThe 5-minute Explanation to HTTPS
    #security
  • Photo by Steve Johnson on Unsplash
    Apr 06 2023 — 5 min readCSS Architecture: The Fundamentals
    #css#front-end

  • Built and designed by Alissa Nguyen a.k.a Tam Nguyen.

    Copyright © 2024 All Rights Reserved.