Simple Dynamic Form Validation Function Using PHP
Tags: javascript, php, mysql, html
Published: 2022-03-22 06:11:52

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

[![Advanced Laravel SAAS Starter Kit with CRUD Generator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyjyev8tz3r8vi2w3on1.png)](https://1.envato.market/5g5QAn)

[Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!](https://1.envato.market/5g5QAn)

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:

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

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

```php
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.

```php
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.

```php
[
	'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:

```php
[
..
	'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:

```php
[
..
	'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:

```php
[
..
	'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:

```php
[
..
	'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:

```php
[
..
	'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
<?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
<?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
<?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](https://ecn-storage.s3.us-west-2.amazonaws.com/articles/simple-dynamic-form-validation-function-using-php-bNsxNu1xKxx980.webp?ctm=1627623514)

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.


[![Advanced Laravel SAAS Starter Kit with CRUD Generator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyjyev8tz3r8vi2w3on1.png)](https://1.envato.market/5g5QAn)

[Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!](https://1.envato.market/5g5QAn)



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