PHP Form Validations with examples [+Github code]
I am back with a new php tutorial and this time it is php form validation but not as usually we do, we have another way to implement php form validation with examples.
Few days back I created a small project called simple php shopping cart with PHP & Mysql. I had also created a login and registration form there and while creating that I have created a different way to use a form validations with php.
Live Demo
Go To Live DemoLet’s discuss the php form validation with the way which provides a nice and clean code.
Local setup of php form validation project
Go to your localhost directory like htdocs or www. Then open your command terminal and run the following command
git clone https://github.com/SATPAL-BHARDWAJ/php-form-validation.git
It will clone the php-form-validation project to your local server.
Now, you need to change a few things, open your code editor and add this project there. Open the file config/include.php and replace the BASE_PATH constant value with your project directory.
For example, my project is in the following directory
htdocs/projects/php-form-validation
So,
define('BASE_PATH', '/projects/php-form-validation');
Save it. And now open your web browser and type following url
localhost/path-to/php-form-validation
Replace “path-to” with your actual directory, if you have any otherwise if you clone this project to the root like htdocs or www directly then use only “/php-form-validation”.
Create php form validation with PHP sessions
I have created a directory called helper and a file under it, called common.php, then I have added a few functions there to handle form validations and other activities.
<?php if( !function_exists('url') ) { function url( $url = null, $parameter = [] ) { echo BASE_PATH."{$url}"; } } if( !function_exists('layout') ) { function layout( $file ) { include_once "./resources/layouts/{$file}.php"; } } if( !function_exists('redirect') ) { function redirect( $path ) { header('location: '.BASE_PATH.$path); exit(); } } if( !function_exists('session') ) { function session( $key, $value = null ) { if ( $value ) { $_SESSION[$key] = $value; } return isset($_SESSION[$key]) ? $_SESSION[$key] : null; } } if( !function_exists('hasSession') ) { function hasSession( $key ) { $keys = is_array($key) ? $key : array($key); $exist = false; foreach($keys as $k) { if(isset($_SESSION[$k])) { $exist = true; } } return $exist; } } if( !function_exists('removeSession') ) { function removeSession( $key ) { $keys = is_array($key) ? $key : array($key); foreach($keys as $k) { if(isset($_SESSION[$k])) { unset($_SESSION[$k]); } } } } if( !function_exists('dd') ) { function dd( ...$data ) { if ( is_array($data) ) { echo '<pre>'; print_r($data); echo '</pre>'; } else { var_dump($data); } die; } } if( !function_exists('formError') ) { function formError( $key ) { if ( isset($_SESSION['errorsBag']) && isset($_SESSION['errorsBag'][$key]) ) { $error = $_SESSION['errorsBag'][$key]; unset($_SESSION['errorsBag'][$key]); return $error; } } } if( !function_exists('HasFormError') ) { function hasFormError( $key ) { if ( isset($_SESSION['errorsBag']) && isset($_SESSION['errorsBag'][$key]) ) { return true; } return false; } } if( !function_exists('setErrorsBag') ) { function setErrorsBag( $key, $value ) { $_SESSION['errorsBag'][$key] = $value; } } if( !function_exists('hasErrorBag') ) { function hasErrorBag() { return isset($_SESSION['errorsBag']) && count($_SESSION['errorsBag']) > 0; } } if( !function_exists('showFormError') ) { function showFormError($key) { if (hasFormError( $key )) { $error = formError( $key ); echo "<div class='invalid-feedback'>*{$error}</div>"; }; } } if( !function_exists('resetErrorBag') ) { function resetErrorBag() { if( isset($_SESSION['errorsBag']) ) { unset($_SESSION['errorsBag']); } } }
Create php form errors in RegisterController
In the app/controller.php we are setting these errors to php sessions. The setErrorBag() function is very helpful here to create new form errors.
We are using a function where we are calling resetErrorBag() to reset old form errors and at the end we are using hasErrorBag() function to know about the latest error if found anything.
The validateAndSanitize( $key ) function allows us to verify our inputs and add errors to the session bag if we have any.
<?php require_once 'config/include.php'; if( $_SERVER['REQUEST_METHOD'] === 'POST' ) { resetErrorBag(); $first_name = validateAndSanitize('first_name'); $last_name = validateAndSanitize('last_name'); $email = validateAndSanitize('email'); $password = validateAndSanitize('password'); $repassword = validateAndSanitize('repassword'); if ( hasErrorBag() ) { redirect('\signup'); } if($password != $repassword){ setErrorsBag('repassword', 'Passwords did not match'); redirect('\signup'); } session('success', 'Form submitted successfully!'); redirect('/signup'); // store to the database here } else { redirect('/error'); } function validateAndSanitize( $key ) { $messages = [ 'first_name' => 'First name is required', 'last_name' => 'Last name is required', 'email' => 'Please enter valid email!', 'password' => 'Password is required', 'repassword' => 'Confirm password is required', ]; if ( $key === 'email' ) { $data = filter_input(INPUT_POST, $key, FILTER_SANITIZE_EMAIL); $var = filter_var($data, FILTER_VALIDATE_EMAIL); if ( $var === false ) { //error : invalid type setErrorsBag($key, $messages[$key]); } } else { $data = filter_input(INPUT_POST, $key, FILTER_SANITIZE_STRING); $var = trim($data); if ( empty($var) ) { //error : required setErrorsBag($key, $messages[$key]); } } return $var; }
Show php form errors on signup page
First thing we need to check is our error bag. So, we can use hasErrorBag() function for that and if it finds the error it will add the class called “was-validated” to the form.
Then Pass the input name to the showFormError( $key ) function and it will return the html code to show the error if there is any.
<div class="container my-5 bg-white p-5"> <form class="row g-3 needs-validation <?php echo hasErrorBag() ? 'was-validated' : ''; ?>" action="<?php url('\app\signup') ?>" method="post" novalidate> <div class="col-md-6"> <label for="validationCustom01" class="form-label">First name</label> <input type="text" class="form-control" name="first_name" id="validationCustom01" required> <?php showFormError('first_name'); ?> </div> <div class="col-md-6"> <label for="validationCustom02" class="form-label">Last name</label> <input type="text" class="form-control" name="last_name" id="validationCustom02" required> <?php showFormError('last_name'); ?> </div> <div class="col-md-12"> <label for="validationCustom03" class="form-label">Email</label> <input type="email" class="form-control" name="email" id="validationCustom03" required> <?php showFormError('email'); ?> </div> <div class="col-md-12"> <label for="validationCustom04" class="form-label">Password</label> <input type="password" class="form-control" name="password" id="validationCustom04" required> <?php showFormError('password'); ?> </div> <div class="col-md-12"> <label for="validationCustom05" class="form-label">Confirm Password</label> <input type="password" class="form-control" name="repassword" id="validationCustom05" required> <?php showFormError('repassword'); ?> </div> <div class="col-12"> <button class="btn btn-primary" type="submit">Submit form</button> </div> </form> </div>
You will definitely find this helpful.
See you in the next learning journey.