Create Your Own PHP Form Validation Library

PHP Form Validation is most important for any html form because with a simple form use can do anything.

PHP Form Validation

PHP form validation is most important any HTML form, because if your form is not validated then the user can do anything with your form. they can submit an empty form, so each company has different requirements and each company can set validations according to has requirements. so you can examine how PHP form validation is important.
php form validation

PHP Form Validation rules  

 In this article we will cover these validation rules:
  • Required rule
  • uniqueEmail rule
  • min_len rule

PHP Form Validation Source Code

index.php


<?php
include "db.php";
include "validation.php";

$validation = new validation;
if(isset($_POST['btn'])){

    $validation->validate('fullName', 'full name', 'required');
    $validation->validate('email', 'Email', 'uniqueEmail|users|required');
    $validation->validate('password', 'Password', 'required|min_len|6');
    if($validation->run()){
        echo "Form is sumitted";
    }

}



?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Form valiations</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
   <div class="container mt-5">
       <div class="row">
           <div class="col-md-5">
               <h3>Create new account</h3><hr>
               <form action="" method="POST">
                   <div class="form-group">
                       <input type="text" name="fullName" class="form-control" placeholder="Enter fullname" value="<?php if($validation->input('fullName')): echo $validation->input('fullName'); endif; ?>">
                       <div class="error text-danger">
                           <?php if(!empty($validation->errors['fullName'])): echo $validation->errors['fullName']; endif; ?>
                       </div>
                   </div>

                   <div class="form-group">
                       <input type="email" name="email" class="form-control" placeholder="Enter email" value="<?php if($validation->input('email')): echo $validation->input('email'); endif; ?>">
                       <div class="error text-danger">
                           <?php if(!empty($validation->errors['email'])): echo $validation->errors['email']; endif; ?>
                       </div>
                   </div>

                   <div class="form-group">
                       <input type="password" name="password" class="form-control" placeholder="Create a new password" value="<?php if($validation->input('password')): echo $validation->input('password'); endif; ?>">
                       <div class="error text-danger">
                           <?php if(!empty($validation->errors['password'])): echo $validation->errors['password']; endif; ?>
                       </div>
                   </div>

                   <div class="form-group">
                       <input type="submit" name="btn" class="btn btn-info" value="Save">
                   </div>
               </form>
           </div>
       </div>
   </div> 
</body>
</html>

db.php


<?php

class db {

    public $connect;
    public function __construct()
    {
        try {

            $this->connect = new PDO("mysql:host=localhost;dbname=example", 'root', '');

        } catch(PDOException $e){
            echo "Connection error: ". $e->getMessage();
        }
    }

}


?>

validation.php


<?php
error_reporting(0);
class validation extends db {

    public $errors = [];

    public function input($field){
        if($_SERVER['REQUEST_METHOD'] == 'POST' || $_SERVER['REQUEST_METHOD'] == 'post'){
            return strip_tags(trim($_POST[$field]));
        } else if($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'get'){
            return strip_tags(trim($_GET[$field]));
        }
    }
    public function validate($field, $label, $rules){

    //    Split rule string on pipe sign
    $allRules = explode("|", $rules);
    $inputField = $this->input($field);
    // Check required rule in the array
    if(in_array("required", $allRules)){
        
        if(empty($inputField)){
            return $this->errors[$field] = $label . " is required";
        }

    }
    // Close required rule

    // Check uniqueEmail rule in the array
    if(in_array('uniqueEmail', $allRules)){

        $uniqueIndex = array_search("uniqueEmail", $allRules);
        $tableIndex  = $uniqueIndex + 1;
        $tableName   = $allRules[$tableIndex];
        $result = $this->connect->prepare(" SELECT * FROM " . $tableName . " WHERE " . $field . " = ? ");
        if($result->execute([$inputField])){
            if($result->rowCount() > 0 ){
                return $this->errors[$field] = $label . " is already exist";
            }
        }

    }
    // Close uniqueEmail rule

    // Check min_len rule in the array
    if(in_array("min_len", $allRules)){
        $minLenIndex = array_search("min_len", $allRules);
        $valueIndex = $minLenIndex + 1;
        $minValue = $allRules[$valueIndex];
        if(strlen($inputField) < $minValue){
            return $this->errors[$field] = $label . " is too short";
        }

    }

    }

    public function run(){
        if(empty($this->errors)){
            return true;
        } else {
            return false;
        }
    }

}

?>

COMMENTS

Name

ajax,2,HTML & CSS,19,JavaScript,1,PHP,11,
ltr
item
webtipstricks: Create Your Own PHP Form Validation Library
Create Your Own PHP Form Validation Library
PHP Form Validation is most important for any html form because with a simple form use can do anything.
https://i.ytimg.com/vi/SFe1flABuCo/hqdefault.jpg
https://i.ytimg.com/vi/SFe1flABuCo/default.jpg
webtipstricks
https://www.webtipstricks.com/2019/06/php-form-validation.html
https://www.webtipstricks.com/
https://www.webtipstricks.com/
https://www.webtipstricks.com/2019/06/php-form-validation.html
true
4027471107773963481
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy