Form Validation and Show Errors using PHP Tutorial

In this tutorial, you can learn to Validate Form Fields and Display Errors using PHP Language. The tutorial aims to provide students and beginners with a reference for validating form fields using some built-in functions of PHP and returning the error validation messages. Here, I will be providing a simple web page script that demonstrates the main goal of this tutorial. The web page's complete source code zip file is also provided and is free to download.

What is Form Validation?

Form Validation is the common process of web or software forms that validates the given values of the end-users. This process checks each value depending on an algorithm or logic of the application if it meets the required pattern, format, etc of the fields. This process often comes with alert messages or error messages to notify the end user that the field validation process fails.

How to Create a Form Validation and Show Error Messages using PHP?

The Form Validation and Show Error Messages can be easily achieved using some useful built-in PHP functions and statements. Here are some PHP functions and statements that became handy for the form validation process:

  • If Statement
  • isset() Function
  • empty() Function
  • filter_var() Function
  • preg_match() Function
  • Try Catch Exception
  • array() Function

These functions and statements are very useful to code the logic and algorithm of the validation process and return validation error messages. Check out the simple web page scripts that I created and provided below to have a much better idea of how to achieve our goal in an actual web application.

Sample Web Page

The following scripts result in a simple web application that contains a simple form for registering member details. The form contains 3 input fields which are the Name, Email, and Contact Number. Each field validates the user-entered values if it is empty and meets the requirements of the fields.

Database Schema

Here is the sample web page database schema named dummy_db with a members table.

  1. -- phpMyAdmin SQL Dump
  2. -- version 5.1.3
  3. -- https://www.phpmyadmin.net/
  4. --
  5. -- Host: 127.0.0.1
  6. -- Generation Time: May 15, 2023 at 04:33 AM
  7. -- Server version: 10.4.24-MariaDB
  8. -- PHP Version: 8.1.5
  9.  
  10. SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
  11. SET time_zone = "+00:00";
  12.  
  13. --
  14. -- Database: `dummy_db`
  15. --
  16.  
  17. -- --------------------------------------------------------
  18.  
  19. --
  20. -- Table structure for table `members`
  21. --
  22.  
  23. CREATE TABLE `members` (
  24. `name` varchar(255) DEFAULT NULL,
  25. `phone` varchar(100) DEFAULT NULL,
  26. `email` varchar(255) DEFAULT NULL
  27.  
  28. --
  29. -- Indexes for dumped tables
  30. --
  31.  
  32. --
  33. -- Indexes for table `members`
  34. --
  35. ALTER TABLE `members`
  36. ADD PRIMARY KEY (`id`);
  37.  
  38. --
  39. -- AUTO_INCREMENT for dumped tables
  40. --
  41.  
  42. --
  43. -- AUTO_INCREMENT for table `members`
  44. --
  45. ALTER TABLE `members`
  46.  

Database Connection

The following script is a PHP file known as db-connect.php. The file contains the codes that connect the application to the database.

  1. <?php
  2. // Database Host name
  3. $host = "localhost";
  4. // Database Username
  5. $username = "root";
  6. // Database Password
  7. $password = "";
  8. // Database Name
  9. $dbname = "dummy_db";
  10.  
  11. try{
  12. // Connect Database
  13. $conn= new MySQLi($host, $username, $password, $dbname);
  14. }catch (Exception $e){
  15. // Display Error if Database Conenction Failed
  16. throw new ErrorException($e->getMessage());
  17. }

Page Interface

Next, here is the Page Interface file script known as index.php. The file contains the page layout and form elements. It also contains the PHP codes that display the error and success messages on the interface if exists.

  1. <?php
  2. session_start();
  3. require_once('form-submit.php')
  4. ?>
  5. <!DOCTYPE html>
  6. <html lang="en">
  7. <meta charset="UTF-8">
  8. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  9. <title>PHP Show Error on Form Submit</title>
  10. <link rel="stylesheet" href="style.css">
  11. <link rel="preconnect" href="https://fonts.googleapis.com">
  12. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  13. <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
  14. </head>
  15. <div class="container">
  16. <h1 id="page-title">PHP Show Error on Form Submit</h1>
  17. <hr id="title_hr">
  18. <div id="form-wrapper">
  19. <!-- Form Wrapper -->
  20. <form action="" method="POST">
  21. <!-- Display Error If Exists -->
  22. <?php if(isset($errors['error']) && !empty($errors['error'])): ?>
  23. <div class="msg-error"><?= $errors['error'] ?></div>
  24. <?php endif; ?>
  25. <!-- Display Error If Exists -->
  26. <!-- Display Success Message If Exists -->
  27. <?php if(isset($_SESSION['success_msg']) && !empty($_SESSION['success_msg'])): ?>
  28. <div class="msg-success"><?= $_SESSION['success_msg'] ?></div>
  29. <?php unset($_SESSION['success_msg']); ?>
  30. <?php endif; ?>
  31. <!-- Display Success Message If Exists -->
  32. <!-- Member's Name Field -->
  33. <div class="field-group">
  34. <label for="name">Name <sup><small class="required-field">*</small></sup></label>
  35. <input type="text" id="name" name="name" autofocus value="<?= $_POST['name'] ?? "" ?>">
  36. <!-- Member's Name Field Error Message -->
  37. <?php if(isset($errors['name']) && !empty($errors['name'])): ?>
  38. <div class="error-msg"><?= $errors['name'] ?></div>
  39. <?php endif; ?>
  40. <!-- Member's Name Field Error Message -->
  41. </div>
  42. <!-- Member's Name Field -->
  43. <!-- Member's Email Field -->
  44. <div class="field-group">
  45. <label for="email">Email <sup><small class="required-field">*</small></sup></label>
  46. <input type="text" id="email" name="email" value="<?= $_POST['email'] ?? "" ?>">
  47. <!-- Member's Email Field Error Message -->
  48. <?php if(isset($errors['email']) && !empty($errors['email'])): ?>
  49. <div class="error-msg"><?= $errors['email'] ?></div>
  50. <?php endif; ?>
  51. <!-- Member's Email Field Error Message -->
  52. </div>
  53. <!-- Member's Email Field -->
  54. <div class="field-group">
  55. <label for="phone">Contact No. <sup><small class="required-field">*</small></sup></label>
  56. <input type="text" id="phone" name="phone" value="<?= $_POST['phone'] ?? "" ?>">
  57. <?php if(isset($errors['phone']) && !empty($errors['phone'])): ?>
  58. <div class="error-msg"><?= $errors['phone'] ?></div>
  59. <?php endif; ?>
  60. </div>
  61. <!-- Form Buttons -->
  62. <div class="btn-group">
  63. <button id="btn-submit" type="submit"><span class="material-symbols-outlined">save</span> Save</button>
  64. <button id="btn-reset" type="reset"><span class="material-symbols-outlined">restart_alt</span> Reset</button>
  65. </div>
  66. <!-- Form Buttons -->
  67. </form>
  68. <!-- Form Wrapper -->
  69. </div>
  70. </div>
  71. </body>
  72. </html>

Stylesheet

Here's the CSS file script known as style.css. The file contains the codes that design the page layout and some elements page interface.

  1. @import url('https://fonts.googleapis.com/css2?family=Dongle:wght@300;400;700&family=Roboto+Mono:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;1,100;1,200;1,300;1,400;1,500;1,600&display=swap" rel="stylesheet');
  2. *{
  3. margin: 0;
  4. padding: 0;
  5. box-sizing: border-box;
  6. font-family: 'Dongle', sans-serif;
  7. font-family: 'Roboto Mono', monospace;
  8. }
  9. ::selection{
  10. color: #fff;
  11. background: #4db2ec;
  12. }
  13. body{
  14. display: flex;
  15. align-items: center;
  16. justify-content: center;
  17. min-height: 100vh;
  18. background: #4facfe;
  19. background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
  20. padding: 2em 0;
  21. }
  22. #page-title{
  23. color: #fff;
  24. text-align: center;
  25. font-weight: 500;
  26. text-shadow: 0px 0px 15px #0000003a;
  27. }
  28. #title_hr{
  29. width:60px;
  30. border: 2px solid #ffffff;
  31. margin: .35em auto;
  32. }
  33. @media (min-width: 780px){
  34. #page-title{
  35. width: 780px;
  36. }
  37. }
  38.  
  39. div#form-wrapper {
  40. width: 600px;
  41. padding: 1em 0.75em;
  42. margin: 2em auto;
  43. background: #fff;
  44. border: 1px solid #d1d1d1;
  45. box-shadow: 0px 0px 10px #00000038;
  46. border-radius: 5px;
  47. }
  48.  
  49. @media (max-width: 650px){
  50. #form-wrapper{
  51. width: 98%;
  52. }
  53. }
  54.  
  55. .field-group {
  56. position: relative;
  57. margin: 0.5em 0;
  58. }
  59.  
  60. .field-group>label,
  61. .field-group>input,
  62. .field-group>.error-msg{
  63. display: block;
  64. width: 100%;
  65. }
  66. .field-group>label{
  67. font-size:1.1rem;
  68. font-weight: 500;
  69. color:#2c2c2c;
  70. margin-bottom:.35em;
  71. }
  72. .field-group .required-field{
  73. color:#e93f3f;
  74. }
  75. .field-group>input {
  76. padding: 0.5em 0.5em;
  77. outline: none;
  78. border: 1px solid #c7c6c6;
  79. line-height: .9rem;
  80. font-size: .9rem;
  81. }
  82. .field-group>input:focus {
  83. border-color: #8ec1d1;
  84. box-shadow: 0px 0px 5px #8ec1d18a;
  85. }
  86. .btn-group {
  87. display: flex;
  88. width: 100%;
  89. justify-content: space-evenly;
  90. }
  91. .btn-group>button {
  92. display: flex;
  93. align-items: center;
  94. justify-content: center;
  95. padding: 0.35em 0.75em;
  96. min-width: 150px;
  97. border: none;
  98. outline: none;
  99. cursor: pointer;
  100. font-size: 1rem;
  101. font-weight: 500;
  102. }
  103.  
  104. button#btn-submit {
  105. color: #fff;
  106. background: #00a1ff;
  107. }
  108. button#btn-submit:hover,
  109. button#btn-submit:focus{
  110. background: #0277bb;
  111. }
  112. button#btn-reset {
  113. background: #ebebeb;
  114. color: #3a3a3a;
  115. }
  116. button#btn-reset:hover,
  117. button#btn-reset:focus {
  118. background: #dddddd;
  119. color: #585858;
  120. }
  121.  
  122. .msg-success,
  123. .msg-error {
  124. padding: 0.75em 1em;
  125. margin-bottom: 0.5em;
  126. background: #d9d2d2;
  127. border-radius: 5px;
  128. font-weight: 400;
  129. color: #fff;
  130. }
  131.  
  132. .msg-error {
  133. background: #ff7979;
  134. }
  135. .msg-success {
  136. background: #448f5b;
  137. }
  138.  
  139. .error-msg {
  140. padding: 0 0.75em;
  141. color: #cb5454;
  142. }
  143.  

Form Validation and Data Insertion

Lastly, here's the PHP file script known as form-submit.php. The file contains the PHP codes that validates each Form Fields. Also, the file contains the data insertion script.

  1. <?php
  2. $errors = [];
  3. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  4. require_once('db-connect.php');
  5.  
  6. // Extracting POST Data
  7. extract($_POST);
  8.  
  9. // Validate Name Field
  10. if(!empty($name)){
  11. if(!preg_match('/^[a-zA-Z\s]+$/', $name)){
  12. $errors['name'] = 'Member Name field only allows letters and spaces.';
  13. }
  14. }else{
  15. $errors['name'] = 'Member Name field is required.';
  16. }
  17. // Validate Email Field
  18. if(!empty($email)){
  19. if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
  20. $errors['email'] = 'Invalid Email Address.';
  21. }
  22. }else{
  23. $errors['email'] = 'Member Email field is required.';
  24. }
  25. // Validate Contact Number Field
  26. if(!empty($phone)){
  27. if(!preg_match('/^[0-9]{11}+$/', $phone)){
  28. $errors['phone'] = 'Member Contact Number field only 11 digit numbers.';
  29. }
  30. }else{
  31. $errors['phone'] = 'Member Contact Number field is required.';
  32. }
  33.  
  34. if(count($errors) <= 0){
  35. // If Validations are successful
  36. // Escape Post Values
  37. $name = htmlspecialchars($conn->real_escape_string($name));
  38. $email = htmlspecialchars($conn->real_escape_string($email));
  39. $phone = htmlspecialchars($conn->real_escape_string($phone));
  40.  
  41. // Member's Databa Insertion Statement
  42. $insert_statment = "INSERT INTO `members` (`name`, `email`, `phone`) VALUES ('{$name}', '{$email}', '{$phone}')";
  43. try{
  44. // Execute Inertion Query
  45. $insert_sql = $conn->query($insert_statment);
  46. }catch(Exception $e){
  47. // Return Error message if Insertion Failed
  48. $errors['error'] = $e->getMessage();
  49. }
  50. if(!isset($errors['error'])){
  51. // store success message using session
  52. $_SESSION['success_msg'] = "New Member's Data has been registered successfully.";
  53. // Reload Page
  54. header('location: ./');
  55. }
  56. }
  57. $conn->close();
  58. }

Snapshots

Here are some snapshots of the overall result of the provided scripts.

Page Interface

Required Fields

Field Validations

Insertion Error

Insertion Success

There you go! I have provided also the complete source code zip file on this website and it is free to download. The download button can be found below this tutorial's content. Feel free to download and modify the source code the way you wanted.

DEMO VIDEO

That's it! I hope this Form Validation and Show Errors using PHP Tutorial will help you with what you are looking for and that you'll find this useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Comments

Submitted byThespywalker (not verified)on Mon, 05/15/2023 - 12:46

Thanks but can these codes work if I have different websites using same one database?
Submitted byspywalker (not verified)on Mon, 05/15/2023 - 13:00

Can it work on different webs using same database?

Add new comment