DEV Community

Code And Deploy
Code And Deploy

Posted on

 

Simple Dynamic Form Validation Function Using PHP

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/simple-dynamic-form-validation-function-using-php

In this tutorial, I code a simple dynamic form validation function using PHP that has the same syntax as Laravel validation. We know that validation is one of the most important before saving it to our database. For example, if your column only has a size of 100 characters allowed but you did not check the maximum characters and your user input more than 100 characters then the data saved will be cut.

These are my basic features in this function:

  • Required - Set field as required and not continue if no inputted value
  • Email - Check field if a valid email
  • Unique - Check field if it is a unique value to your database table (Useful to check if the value is not yet existing in your table)
  • Max - Check the field maximum length
  • Min - Check the field minimum length

How to use this feature?

Kindly check the below code on how to use this function:

// Validate the data
$validation = validate($_REQUEST, [
    'email' => 'required|email|unique:employees|min:2|max:100',
    'first_name' => 'required|min:2|max:100',
    'last_name' => 'required|min:2|max:100',
    'address' => 'required|min:2|max:250'
]);
Enter fullscreen mode Exit fullscreen mode

As you can see above we call the validate() function these parameters:

function validate($input, $rules) {}
Enter fullscreen mode Exit fullscreen mode

$input - This is an array type and it is suitable for $_REQUEST and $_POST Super Global variable. Below is the sample format of an array.

Array
(
    [email] => email@gmail.com
    [first_name] => Ronard
    [last_name] => Cauba
    [address] => Dumaguete City, Negros Oriental, Philippines
)
Enter fullscreen mode Exit fullscreen mode

$rules - This is an array type with field validation value. Below is the sample array value.

[
    'email' => 'required|email|unique:employees|min:2|max:100',
    'first_name' => 'required|min:2|max:100',
    'last_name' => 'required|min:2|max:100',
    'address' => 'required|min:2|max:250'
]
Enter fullscreen mode Exit fullscreen mode

Validation Syntax

The array key name which is the field name from the $input parameter and the array key name of $rules parameter must the same. As you can see the above example for $input & $rules parameters.

Required Syntax - if your field needs to be required then you must add "required" to the $rules parameter with your field name for example:

[
..
    'email' => 'required'
..
]
Enter fullscreen mode Exit fullscreen mode

Email Syntax - if your field needs to validate if the email is valid then you must add "email" to the $rules parameter with your field name for example:

[
..
    'email' => 'required|email'
..
]
Enter fullscreen mode Exit fullscreen mode

NOTE: As you can see we have required and email validation now for the email field. So you need to have a separator "|" (bar line)

Unique Syntax - if your field must be a unique value to your table then you must add "unique:{table_name}" so if your table name is "users" then it should be like this:

[
..
    'email' => 'unique:users'
..
]
Enter fullscreen mode Exit fullscreen mode

Min Syntax - if your field has a minimum amount of characters then you must add "min:{minimum_number}". Here is the sample code below:

[
..
    'email' => 'min:10'
..
]

Enter fullscreen mode Exit fullscreen mode

Max Syntax - if your field has a maximum amount of characters then you must add "max:{maximum_number}". Here is the sample code below:

[
..
    'email' => 'max:100'
..
]
Enter fullscreen mode Exit fullscreen mode

Complete Form Validation Functions

Now you have the basic validation for your form. Now I will provide the complete function source code for you to use.

First, config.php

<?php
    //set the servername
    define("SERVER_NAME", "localhost");
    //set the server username
    define("SERVER_UNAME", "root");
    // set the server password (you must put password here if your using live server)
    define("SERVER_UPASS", "");
    // set the table name
    define("SERVER_DB", "demos");

    // Include functions file
    require_once 'functions.php';

    // Connect to database
    $db = connectDB();
?>
Enter fullscreen mode Exit fullscreen mode

Second, functions.php

<?php

    function connectDB() 
    {
        $db = new mysqli(SERVER_NAME, SERVER_UNAME, SERVER_UPASS, SERVER_DB);

        if ($db->connect_errno) {
          echo "Failed to connect to MySQL: " . $db->connect_error;
          exit();
        }

        return $db;
    }

    function validate($input, $rules) 
    {
        $errors = [];

        if(is_array($input)):
            foreach($rules as $fieldName=>$value):
                $fieldRules = explode("|", $value);

                foreach($fieldRules as $rule):

                    $ruleValue = _getRuleSuffix($rule);
                    $rule = _removeRuleSuffix($rule);

                    if($rule == "required" && isEmptyFieldRequired($input, $fieldName)):
                        $errors[$fieldName]['required'] = _removeUnderscore(ucfirst($fieldName)) . " field is required.";
                    endif;

                    if($rule == "email" && !isEmailValid($input, $fieldName)):
                        $errors[$fieldName]['email'] = _removeUnderscore(ucfirst($fieldName)) . " field is invalid.";
                    endif;

                    if($rule == "min" && isLessThanMin($input, $fieldName, $ruleValue)):
                        $errors[$fieldName]['max'] = _removeUnderscore(ucfirst($fieldName)) . " field is less than " . $ruleValue . " characters of the minimum length.";
                    endif;

                    if($rule == "max" && isMoreThanMax($input, $fieldName, $ruleValue)):
                        $errors[$fieldName]['max'] = _removeUnderscore(ucfirst($fieldName)) . " field is more than " . $ruleValue . " characters of the maximum length.";
                    endif;

                    if($rule == "unique" && !isRecordUnique($input, $fieldName, $ruleValue)):
                        $errors[$fieldName]['unique'] = _removeUnderscore(ucfirst($fieldName)) . " field is already exists.";
                    endif;

                endforeach;
            endforeach;
        endif;

        return $errors;

    }

    function isEmptyFieldRequired($input, $fieldName) 
    {
        return $input[$fieldName] == "" || empty($input[$fieldName]);
    }

    function isLessThanMin($input, $fieldName, $value) 
    {
        return strlen($input[$fieldName]) < $value; 
    }

    function isMoreThanMax($input, $fieldName, $value) 
    {
        return strlen($input[$fieldName]) > $value;
    }

    function isRecordUnique($input, $fieldName, $value) 
    {   
        // Connect to database
        $db = connectDB();

        // SQL Statement
        $sql = "SELECT * FROM ".$value." WHERE ".$fieldName."='".$input[$fieldName]."'";

        // Process the query
        $results = $db->query($sql);

        // Fetch Associative array
        $row = $results->fetch_assoc();

        // Close db connection
        $db->close();

        // If the result is not array so the record is unique
        return !is_array($row);
    }

    function isEmailValid($input, $fieldName) 
    {
        $email = $input[$fieldName];

        if(!empty($email) || $email != ""):
            return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $email)) ? FALSE : TRUE;
        else:
            return TRUE;
        endif;
    }


    function _removeUnderscore($string) 
    {
        return str_replace("_", " ", $string);
    }

    function _removeRuleSuffix($string) 
    {
        $arr = explode(":", $string);

        return $arr[0];
    }

    function _getRuleSuffix($string) 
    {
        $arr = explode(":", $string);

        return isset($arr[1])?$arr[1]:null;
    }

?>
Enter fullscreen mode Exit fullscreen mode

Third, code implementation

<?php
    // include config file
    require_once 'config.php';

    // Validate the data
    $validation = validate($_REQUEST, [
        'email' => 'required|email|unique:employees|min:2|max:100',
        'first_name' => 'required|min:2|max:100',
        'last_name' => 'required|min:2|max:100',
        'address' => 'required|min:2|max:250'
    ]);

    // Defined $result as array
    $result = [];

    // Check if no validation errors
    if(!count($validation)):
       //do something here
    else:
       //do something here to display the errors
       $result['has_error'] = 1;
       $result['errors'] = $validation;
    endif;

    // Encode array into json format (this is useful if your using ajax)
    echo json_encode($result);
?>
Enter fullscreen mode Exit fullscreen mode

Fourth, Result when the error occurred.

simple-dynamic-form-validation-function-using-php

That's it I hope this basic function may help your form validations dynamically.I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/simple-dynamic-form-validation-function-using-php if you want to download this code.

NOTE: In this tutorial, I'm using ajax so just adjust your code to fit with not ajax functionality.

Thank you for reading. Happy coding :)

Top comments (0)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another “Coder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.