PHP Basic Form Validation Tutorial

In this tutorial we learn how to process forms with simple validations to enhance the security of our application.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is form validation?

Form validation is when we evaluate form fields against specific requirements during processing. We might want to check if a password is longer than 7 characters, or if an email address contains the @ symbol.

There is no one-size-fits-all solution to form validation. It depends on the form fields and what we want to evaluate.

Simple form validation

For our example, we want to evaluate three fields:

  1. Username. The username field is required and must be equal to or longer than 3 characters.
  2. Email. The email field is required and must be a valid email address.
  3. Password. The password field must be longer than 7 characters.
Example: html form
<html>
<body>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    Name:* <input type="text" name="username"><br>
    Email:* <input type="email" name="email"><br>
    Password:* <input type="password" name="password"><br><br>
    <input type="submit">
</form>

</body>
</html>

In the html form above, we use $_SERVER["PHP_SELF"] to submit the form to the current page.

How to validate form submission

Because the form page submits to itself, we must evaluate if the form has actually been submitted before we can process the fields.

A simple way to do this, is to evaluate the $_SERVER['REQUEST_METHOD'] superglobal result.

Example: form submission check
<html>
<body>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    Name:* <input type="text" name="username"><br>
    Email:* <input type="email" name="email"><br>
    Password:* <input type="password" name="password"><br><br>
    <input type="submit">
</form>

</body>
</html>

<?php

// Check if form has been submitted
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validations here
}

?>
How to validate text

Let’s start our validations with the username field. As mentioned earlier in the tutorial lesson, the username field must not be empty and equal to or longer than three characters.

In this validation, we need two functions:

  • empty() will evaluate if the field is empty.
  • strlen() will evaluate how long a string is.
Example: username validation
<?php

// Check if form has been submitted
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Get username
    $username = $_POST['username'];
    // Validate username
    if(empty($username) || strlen($username) < 3) {
        echo "<p>Name is required and must be longer than 3 characters.</p>";
    }

}

?>
How to validate an email address

Next, we will check if the email address is valid. PHP provides us with the filter_var() function to validate an email address. The filter must be FILTER_VALIDATE_EMAIL.

Syntax:
 filter_var(email_address, FILTER_VALIDATE_EMAIL);

The filter_var() function will return true if the email is valid, and false if not.

Example:
<?php

// Check if form has been submitted
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Get username
    $username = $_POST['username'];
    // Validate username
    if(empty($username) || strlen($username) < 3) {
        echo "<p>Name is required and must be longer than 3 characters.</p>";
    }

    // Get email
    $email = $_POST['email'];
    // Validate email
    if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<p>Please provide a valid email address.</p>";
    }

}

?>
How to validate a password

Lastly, we will check if the password exists and is longer than 7 characters. This validation is the same as the one we did on the username.

Example:
<?php

// Check if form has been submitted
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Get username
    $username = $_POST['username'];
    // Validate username
    if(empty($username) || strlen($username) < 3) {
        echo "<p>Name is required and must be longer than 3 characters.</p>";
    }

    // Get email
    $email = $_POST['email'];
    // Validate email
    if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<p>Please provide a valid email address.</p>";
    }

    // Get password
    $password = $_POST['password'];
    // Validate password
    if(empty($password) || strlen($password) < 7) {
        echo "<p>Password is required and must be longer than 7 characters.</p>";
    }

}

?>

In almost all cases we would do some further regular expression matches to check for uppercase letters, special characters, numbers etc.

How to pre-validate a function

It’s a good idea to clean up and sanitize the input coming from a form before validating.

For this clean up, we can use the following functions:

  • trim() will remove all extra whitespace from the beginning and end of a string.
  • htmlspecialchars() will replace certain characters such as <> etc.

Because we are going to use these more than twice, we will wrap it inside a function.

Example:
function preVal($str) {
	return trim(htmlspecialchars($str));
}

The function receives a string, cleans it up, and returns it to us for further processing. We can use it when we access form data for the first time.

Example:
<?php

// Check if form has been submitted
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Get username
    $username = preVal($_POST['username']);
    // Validate username
    if(empty($username) || strlen($username) < 3) {
        echo "<p>Name field is required and must be longer than 3 characters.</p>";
    }

    // Get email
    $email = preVal($_POST['email']);
    // Validate email
    if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<p>Please provide a valid email address.</p>";
    }

    // Get password
    $password = preVal($_POST['password']);
    // Validate password
    if(empty($password) || strlen($password) < 7) {
        echo "<p>Password is required and must be longer than 7 characters.</p>";
    }

}

// Clean up
function preVal($str) {
	return trim(htmlspecialchars($str));
}

?>

There is a lot more to form validation in PHP, particularly when we interact with databases. A common example of this would be mysqli_real_escape_string() that removes special characters for use in an SQL statement.

How to make your inputs sticky

Sticky inputs are input fields that remember any previously entered data if the user makes a mistake. It’s likely that you have encountered this annoying behavior before, submitting a form only to have to re-enter all the information because of a simple mistake.

The solution is quite simple. We first check if the user has entered any data, if so, we echo the data back to the form.

Example:
<?php

if(isset($_POST['username'])) {
	echo $_POST['username'];
}

?>

This is done within the value=“” parameter of the html input field.

Example: inline sticky input
 <input type="text" name="username" value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>">

Even though you can make password fields sticky, we strongly recommend not doing so.

Example:
<html>
<body>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    Name:* <input type="text" name="username" value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>"><br>
    Email:* <input type="email" name="email" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>"><br>
    Password:* <input type="password" name="password"><br><br>
    <input type="submit">
</form>

</body>
</html>

<?php

// Check if form has been submitted
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Get username
    $username = preVal($_POST['username']);
    // Validate username
    if(empty($username) || strlen($username) < 3) {
        echo "<p>Name field is required and must be longer than 3 characters.</p>";
    }

    // Get email
    $email = preVal($_POST['email']);
    // Validate email
    if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<p>Please provide a valid email address.</p>";
    }

    // Get password
    $password = preVal($_POST['password']);
    // Validate password
    if(empty($password) || strlen($password) < 7) {
        echo "<p>Password is required and must be longer than 7 characters.</p>";
    }

}

// Clean up
function preVal($str) {
	return trim(htmlspecialchars($str));
}

?>

Most websites and applications have sticky form data. If a form is short and uncomplicated, users may not mind that much when it’s not sticky.

If a form is longer or more complicated, most users will simply leave the site instead of refilling the form.

Summary: Points to remember

This tutorial lesson only demonstrates simple form validation to introduce the concept. In most cases you will be working with frameworks, such as Laravel, that have their own validation methods.