Understanding the Basics of HTML Login Forms
Updated: 11-Apr-2024 / Tags: HTML and CSS / Views: 125 - Author: George
Introduction
In today's article I am going to explain the anatomy of a simple HTML login form. I am going to show you the elements that make's up a login form, and how to catch the submitted data first with PHP, and then with JavaScript.
Quick Answer
A login form is a common feature on websites and applications that allows users to access restricted areas or features by providing their credentials, typically a username/email and password. Let's see the elements needed to build a login form.
- Username or Email Field: In this field the user enters their username or email depending on the website's or application's preferences.
- Password Field: This is where users input their password. Passwords are usually masked for security reasons, showing asterisks or dots instead of the actual characters.
- Submit Button: This button triggers the submission of the login data. When the user clicks on the Submit Button the form sends the entered data to the server for validation.
- Forgot Password Link: Often included below the password field, this link directs users to a page or process where they can reset their password if they've forgotten it.
- Error Messages: If there are errors during the validation process the form will display an error of what went wrong so the user can change their input.
- Validation: The form should include validation mechanisms to ensure that users enter valid information. For example, it might check if the username/email is in the correct format or if the password meets certain criteria (e.g., minimum length).
A Basic Login Form
Below, we have an example of a simple HTML login form. The form includes a username input field, a password input field, and a submit button. Additionally, an error is displayed when something goes wrong during the form submission process.
Now let's see the html code that makes up the above login form. Here we have a basic login form structure, this is the minimum code that we need to make the form functional.
<form action="" method="post">
<input type="text" name="username" value="" placeholder="Username:">
<input type="password" name="password" value="" placeholder="Password:">
<input type="submit" name="submit" value="Login">
<p class="error">This is an error</p>
</form>
Now let's explain what's going on in our HTML code.
-
The Form Element
<form action="" method="post"></form>
The form element is used to create an HTML form for user input.
The action attribute specifies where to send the form-data when the form is submitted. In this case, it is empty (action=""), meaning it will submit to the same page.
Example: If the action attribute is set to action="script.php", this means that the form data are submitted to the script.php file.
The method attribute specifies the HTTP method to use when sending form-data. Here, it is set to post, which means the form data is sent to the server as a POST request.
-
The Input Elements
<input type="text" name="username" value="" placeholder="Username:"> <input type="password" name="password" value="" placeholder="Password:">
Input elements are used to create various form controls, such as text fields, password fields, buttons, etc.
The type Attribute specifies the type of input control. In this form, there are two types used:
- text: Creates a single-line text input field.
- password: Creates a password input field (text is masked for security).
The name attribute specifies the name of the input control. This is used to identify the input data when the form is submitted.
The value attribute specifies the initial value of the input control. In this case, both value attributes are empty, meaning the fields start empty.
The placeholder attribute provides a hint or example text that is displayed in the input field when it is empty.
-
The Submit button
<input type="submit" name="submit" value="Login">
type="submit": Creates the submit button.
name="submit": When setting name="submit", allows you to identify that particular button on the server-side when the form is submitted. This means that we will check for a submit value inside the $_POST variable. You will see in the PHP code further down.
value="login": Sets the text displayed on the submit button to "Login".
-
The Error Placeholder
<p class="error">This is an error</p>
This element will serve as a placeholder and will be populated in the first example with PHP, and in the second example with JavaScript.
Handling the login form data with PHP
In this example, we are going to see how to capture the data with PHP and display it on the screen. Additionally, we will implement validation that checks the fields for empty values and displays an error.
Please type something in the form and try it out.
The PHP Code
We mentioned earlier that an empty action attribute, action="", instructs the browser to send the form data to the same file, effectively reloading the page. This is why we need to include our PHP code in the same page; this allows us to capture the form data, typically before the HTML <!DOCTYPE> declaration.
<?php
$error = "";
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) || empty($password)){
$error = "Wrong username or password";
}else{
echo "Your username is: {$username} and your password is: {$password}";
}
}
?>
<form action="" method="post">
<input type="text" name="username" value="" placeholder="Username:">
<input type="password" name="password" value="" placeholder="Password:">
<input type="submit" name="submit" value="Login">
<p class="error">This is an error</p>
</form>
Let's break down the PHP code.
-
Initialization of Error Variable:
$error = "";
We start by initializing an empty string variable called $error to hold any error messages.
-
Form Submission Check:
if(isset($_POST['submit'])){
Next, we check if the form has been submitted by using the isset() function to determine if the 'submit' button was clicked.
-
Retrieve Form Data
$username = $_POST['username']; $password = $_POST['password'];
If the submit button is clicked, we proceed to retrieve the values entered into the 'username' and 'password' fields using the $_POST superglobal array. We store these values in the variables $username and $password, respectively."
-
Validation Check:
if(empty($username) || empty($password)){ $error = "Wrong username or password"; }
Next, we perform a validation check to ensure that both the username and password fields are not empty. We use the empty() function to check if either $username or $password is empty. If either field is empty, we set the $error variable to 'Wrong username or password', indicating that the user needs to provide both a username and a password.
-
Output Message:
else{ echo "Your username is: {$username} and your password is: {$password}"; }
If both fields contain data, meaning they are not empty, we proceed to output a message to the user. This message includes the entered username and password, interpolated into the string using curly braces {}
Handling the login form data with JavaScript
In this example, we will learn how to retrieve the submitted data with JavaScript. Similar to the previous example, we will also check for empty values and display them on the screen. Feel free to try out the form to see it in action.
The JavaScript Code
Below is the JavaScript code responsible for capturing, validating, and displaying the data on the screen. It's important to place this script after the HTML code for the form to function correctly.
To include JavaScript within HTML, we enclose the code within <script></script> tags."
<script>
document.forms["login-form"]
.addEventListener("submit", catchData);
function catchData(e){
e.preventDefault();
let error = document.querySelector(".error");
let output = document.querySelector(".output");
let username = this.username.value;
let password = this.password.value;
if(username === "" || password === ""){
error.innerHTML = "Wrong username or password";
output.innerHTML = "";
}else{
output.innerHTML = `
Your username is: ${username}
and your password is: ${password}
`;
error.innerHTML = "";
}
}
</script>
Let's analyze the above javascript code.
-
Event Listener Setup:
document.forms["login-form"].addEventListener("submit", catchData);
We start by adding an event listener to the 'submit' event of the form with the name 'login-form'. When the form is submitted, the function catchData will be executed.
-
Preventing Default Form Submission:
function catchData(event){ event.preventDefault();
Within the catchData function, we first prevent the default form submission behavior using event.preventDefault(). This ensures that the form data is not submitted to the server in the traditional manner, allowing us to handle it with JavaScript instead.
-
Variable Initialization:
let error = document.querySelector(".error"); let output = document.querySelector(".output");
We then initialize two variables, error and output, by selecting elements with the classes 'error' and 'output', respectively, from the DOM. These elements will be used to display error messages and the output data
-
Fetching Form Data:
let username = this.username.value; let password = this.password.value;
Next, we retrieve the values entered into the 'username' and 'password' fields of the form using this.username.value and this.password.value, respectively. Here, this refers to the form itself, and we access the input fields by their name attributes.
-
Validation Check:
if(username === "" || password === ""){ error.innerHTML = "Wrong username or password"; output.innerHTML = ""; }
We perform a validation check to ensure that both the username and password fields are not empty. If either field is empty, we set the innerHTML of the error element to 'Wrong username or password', indicating that the user needs to provide both a username and a password. We also clear the output element to remove any previous output.
-
Output Display:
else{ output.innerHTML = ` Your username is: ${username} and your password is: ${password} `; error.innerHTML = ""; }
If both fields contain data, meaning they are not empty, we set the innerHTML of the output element to display the entered username and password in a formatted message. Also we clear the error placeholder from any previous error message.
Summary
In this tutorial, we covered the HTML code for creating a login form and explained how to fetch and process submitted data using PHP and JavaScript. We implemented validation to display an error message when a field was left empty. Additionally, we demonstrated how to display the submitted username and password on the screen when the form was successfully submitted.
Thanks for reading.
I hope you find the article helpful, and informative.
Please leave a comment if you find any errors, so i can update the page with the correct code.
Comment section
You can leave a comment, it will help me a lot.
Or you can just say hi. 😉