Table of contents

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'
]);

 

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

function validate($input, $rules) {}

 

$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
)

 

$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'
]

 

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'
..
]

 

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'
..
]

 

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'
..
]

 

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'
..
]

 

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'
..
]

 

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();
?>

 

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;
	}

?>

 

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);
?>

 

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.

 

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 :)