PHP 8 Server Side Form Validation Tutorial Example
The primary aim of this tutorial is to make you aware of using the HTML Form Elements and an easy way to access those fields with PHP.
We will create the form with different input fields such as text, select drop-down, radio buttons, checkboxes, and text area. The server-side validation will be added to these inputs, and the user will be notified when any error occurs on form submission.
Create Simple HTML Form
Set up the form using <form>
tag with method post.
The Bootstrap form component is used to design the form elements, be it text, radio button, select option, checkboxes, or text area.
The name attribute communicates with PHP script and helps in implementing the simple validation in PHP.
For the checkboxes, define the name value with array []
sign to store multiple values.
<form action="" method="post">
<div class="form-group row">
<label class="col-sm-4 col-form-label">Name</label>
<div class="col-sm-8">
<input type="text" name="name" class="form-control">
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Email</label>
<div class="col-sm-8">
<input type="email" name="email" class="form-control">
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Education</label>
<div class="col-sm-8">
<select id="education" name="education" class="form-control">
<option selected="" disabled>...</option>
<option value="Graduation">Graduation</option>
<option value="Post Graduation">Post Graduation</option>
</select>
</div>
</div>
<fieldset class="form-group">
<div class="row">
<legend class="col-form-label col-sm-4 pt-0">Gender</legend>
<div class="col-sm-8">
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="male" name="gender" value="Male" class="custom-control-input">
<label class="custom-control-label" for="male">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="female" name="gender" value="Female" class="custom-control-input">
<label class="custom-control-label" for="female">Female</label>
</div>
</div>
</div>
</fieldset>
<div class="form-group row">
<div class="col-sm-4">Hobbies</div>
<div class="col-sm-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" name="hoby[]" value="Drawing" class="custom-control-input" id="drawing">
<label class="custom-control-label" for="drawing">Drawing</label>
</div>
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" name="hoby[]" value="Singing" class="custom-control-input" id="singing">
<label class="custom-control-label" for="singing">Singing</label>
</div>
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" name="hoby[]" value="Dancing" class="custom-control-input" id="dancing">
<label class="custom-control-label" for="dancing">Dancing</label>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Comment</label>
<div class="col-sm-8">
<textarea class="form-control" name="comment" id="comment" rows="4"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12 mt-3">
<button type="submit" name="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</div>
</form>
Server Side Form Validation in PHP
Set the empty variable these variables hold the error messages that we will show to the users if any error occurs.
Verify if the form is set or not using the isset()
function.
Use the $_POST
super-global variable, and It interacts with form’s method=”post” attribute to get the form data when the user submits the form by clicking on the submit button.
To protect against XSS attacks, we created a custom function checkInput(). It takes input data as a parameter and processes the input data by using trim, stripslashes, and htmlspecialchars()
built-in PHP function.
The empty()
function checks whether the input is empty or not if the variable is empty, display the error message to the user by wrapping the error message in HTML div.
The preg_match()
function finds string for a pattern, and It returns true if a pattern exists and else returns false. We used it for name validation and email validation.
<?php
// Error messages
$nameEmptyErr = "";
$emailEmptyErr = "";
$educationEmptyErr = "";
$genderEmptyErr = "";
$hobyEmptyErr = "";
$commentEmptyErr = "";
$nameErr = "";
$emailErr = "";
if(isset($_POST["submit"])) {
// Set form variables
$name = checkInput($_POST["name"]);
$email = checkInput($_POST["email"]);
$education = checkInput($_POST["education"]);
$gender = checkInput($_POST["gender"]);
$hoby = $_POST["hoby"];
$comment = checkInput($_POST["comment"]);
// Name validation
if(empty($name)){
$nameEmptyErr = '<div class="error">
Name can not be left blank.
</div>';
} // Allow letters and white space
else if(!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = '<div class="error">
Only letters and white space allowed.
</div>';
} else {
echo $name . '<br>';
}
// Email validation
if(empty($email)){
$emailEmptyErr = '<div class="error">
Email can not be left blank.
</div>';
} // E-mail format validation
else if (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $email)){
$emailErr = '<div class="error">
Email format is not valid.
</div>';
} else {
echo $email . '<br>';
}
// Select option validation
if(empty($education)){
$educationEmptyErr = '<div class="error">
Tell us about your education.
</div>';
} else {
echo $education . '<br>';
}
// Radio button validation
if(empty($gender)){
$genderEmptyErr = '<div class="error">
Specify your gender.
</div>';
} else {
echo $gender . '<br>';
}
// Checkbox validation
if(!empty($hoby)){
foreach($_POST['hoby'] as $val){
echo $val . '<br>';
}
} else {
$hobyEmptyErr = '<div class="error">
What are your hobbies.
</div>';
}
// Text-area validation
if(empty($comment)){
$commentEmptyErr = '<div class="error">
This field is required.
</div>';
} else {
echo $comment . '<br>';
}
}
function checkInput($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
?>
Add the custom CSS for styling the form and error messages.
.container {
max-width: 700px;
margin: 50px auto;
}
form {
border: 1px solid #1A33FF;
background: #ecf5fc;
padding: 40px 50px 45px;
}
.form-control:focus {
border-color: #000;
box-shadow: none;
}
.error {
color: red;
font-weight: 400;
display: block;
padding: 6px 0;
font-size: 14px;
}
.form-control.error {
border-color: red;
padding: .375rem .75rem;
}
We defined the form_validation.php in different file so import it inside the form file to make the validation work with PHP form.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Form Validation in PHP</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container mt-5">
<h2 class="text-center mb-4">Demo Form Validation in PHP 8</h2>
<!-- Form validation script -->
<?php include('form_validation.php'); ?>
<!-- Contact form -->
<form action="" method="post" novalidate>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Name</label>
<div class="col-sm-8">
<input type="text" name="name" class="form-control">
<!-- Error -->
<?php echo $nameEmptyErr; ?>
<?php echo $nameErr; ?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Email</label>
<div class="col-sm-8">
<input type="email" name="email" class="form-control">
<!-- Error -->
<?php echo $emailEmptyErr; ?>
<?php echo $emailErr; ?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Education</label>
<div class="col-sm-8">
<select id="education" name="education" class="form-control">
<option selected="" disabled>...</option>
<option value="Graduation">Graduation</option>
<option value="Post Graduation">Post Graduation</option>
</select>
<!-- Error -->
<?php echo $educationEmptyErr; ?>
</div>
</div>
<fieldset class="form-group">
<div class="row">
<legend class="col-form-label col-sm-4 pt-0">Gender</legend>
<div class="col-sm-8">
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="male" name="gender" value="Male" class="custom-control-input">
<label class="custom-control-label" for="male">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="female" name="gender" value="Female" class="custom-control-input">
<label class="custom-control-label" for="female">Female</label>
</div>
<!-- Error -->
<?php echo $genderEmptyErr; ?>
</div>
</div>
</fieldset>
<div class="form-group row">
<div class="col-sm-4">Hobbies</div>
<div class="col-sm-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" name="hoby[]" value="Drawing" class="custom-control-input" id="drawing">
<label class="custom-control-label" for="drawing">Drawing</label>
</div>
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" name="hoby[]" value="Singing" class="custom-control-input" id="singing">
<label class="custom-control-label" for="singing">Singing</label>
</div>
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" name="hoby[]" value="Dancing" class="custom-control-input" id="dancing">
<label class="custom-control-label" for="dancing">Dancing</label>
</div>
<!-- Error -->
<?php echo $hobyEmptyErr; ?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Comment</label>
<div class="col-sm-8">
<textarea class="form-control" name="comment" id="comment" rows="4"></textarea>
<!-- Error -->
<?php echo $commentEmptyErr; ?>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12 mt-3">
<button type="submit" name="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</div>
</form>
</div>
</body>
</html>
Conclusion
Form validation is an essential step in web development. Security must be considered to protect against XSS attacks, especially if you have to store the form data to a database.
In this tutorial, we learned how to create and validate a form using PHP and show error messages.
I hope you loved this tutorial, and you can find the php form validation example code on GitHub.