{"id":20645488,"url":"https://github.com/pedrohenriques/php_datavalidator","last_synced_at":"2026-04-18T08:03:40.217Z","repository":{"id":57037415,"uuid":"65237183","full_name":"PedroHenriques/PHP_DataValidator","owner":"PedroHenriques","description":"A PHP library that allows for an easy and customizable way to validate data.","archived":false,"fork":false,"pushed_at":"2016-08-10T17:57:04.000Z","size":22,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-17T09:33:48.879Z","etag":null,"topics":["data-validation","datavalidator","php-library"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PedroHenriques.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-08-08T20:34:28.000Z","updated_at":"2017-05-07T16:44:45.000Z","dependencies_parsed_at":"2022-08-23T21:00:31.380Z","dependency_job_id":null,"html_url":"https://github.com/PedroHenriques/PHP_DataValidator","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PedroHenriques%2FPHP_DataValidator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PedroHenriques%2FPHP_DataValidator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PedroHenriques%2FPHP_DataValidator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PedroHenriques%2FPHP_DataValidator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PedroHenriques","download_url":"https://codeload.github.com/PedroHenriques/PHP_DataValidator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242714052,"owners_count":20173581,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["data-validation","datavalidator","php-library"],"created_at":"2024-11-16T16:20:03.206Z","updated_at":"2026-04-18T08:03:40.167Z","avatar_url":"https://github.com/PedroHenriques.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PHP Data Validator - Easy to Use and Customizable\n\nA PHP library that allows for an easy and customizable way to validate data.  \n\nThe code will run through an array of data and for each item will execute the specified validations. In the end any validations that failed will generate an error message that you can display.  \n\nAll the validations and error messages can be customized, even the default ones, and you can create new ones \"on the fly\" very easily.  \n\n## Instructions\n\n### Setup\n\n#### =\u003e Composer:\n\nAdd the following to your project's `composer.json` file:\n```\n{\n    \"require\": {\n        \"pedrohenriques/data-validator\": \"1.*\"\n    }\n}\n```  \nReplacing the version with your preference. \n\n#### =\u003e Manual:\n\n1. Copy the `src` folder into your project.\n2. Reference the `DataValidator.php` file on the webpages you wish to use the Data Validator using, for example, `require_once(\"path/to/DataValidator.php\")`.\n\n\u003cbr\u003e\n### Using the Data Validator\n\nIn order to use the Data Validator create an instance of the DataValidator class using the code:  \n```\nuse DataValidator\\DataValidator;\n\n$validator = new DataValidator([string $json_path]);\n```  \n\nWith:  \n- **$json_path**: String with the path to the `error_msg.json` file. This file contains the default error messages for each validation type.  \nIf a path isn't provided the code will assume that the file is located at `src/data/error_msg.json`.\n\n\u003cbr\u003e\nOnce the class has been instantiated, the code `$validator-\u003evalidate(array $data, array $validations[, $single_fail]);` will execute the validations and generate any error messages.  \n\nWith:   \n- **$data**: Array with the data to be validated.\u003cbr\u003e\u003cbr\u003e\n- **$validations**: Array with the desired validations for each of the $data entries (see below for the syntax).\u003cbr\u003e\u003cbr\u003e\n- **$single_fail**: Boolean that controls whether all validations for a $data entry should be executed, or if they should stop when 1 fails.  \n`True` will stop a $data entry's validations as soon as 1 fails and `False` will execute all validations for a $data entry, regardless of how many fail.  \nBy default the code will assume the value `False`.\n\n\u003cbr\u003e\n#### =\u003e `$validations` parameter syntax:  \n\nThe complete syntax is `$validations = [\"field;alias\" =\u003e [\"check_type1;value1;value2...\", \"check_type2;value1;value2...\", ...], ...]` where:  \n\n- **field**: The name of the desired $data entry. The names must match in both the $data and $validations array.\u003cbr\u003e\u003cbr\u003e\n- **alias**: [optional] The alias for the field.  \nIf provided, the alias will be used in the error messages instead of the field name.  \nIf not provided, the field name will be used in the error messages.\u003cbr\u003e\u003cbr\u003e\n- **check_type**: The validation name for the check in question.\u003cbr\u003e\u003cbr\u003e\n- **value**: One value that will be made available to the validation code and the error messages.  \nIf the desired value is one of the $data entries use the format `%field%`, which will be replaced by that field's $data entry.\n\n\u003cbr\u003e\n#### =\u003e Default Validations:  \n\nThis repository comes with the following validations available:  \n\nCheck Type | Description | Values\n--- | --- | ---\n`date` | Checks if the $data entry is a valid date, according to any of the PHP accepted formats | none\n`date_f` | Checks if the $data entry is a valid date, according to specific formats | the accepted formats separated by `;`\u003cbr\u003e\u003cbr\u003eThe formats should follow PHP's date format\n`email` | Checks if the $data entry is a valid email format | none\n`gr_eq_th` | Checks if the $data entry is greater or equal than the validation value (as floats) | the number representing the floor for the check\n`gr_th` | Checks if the $data entry is greater than the validation value (as floats) | the number representing the floor for the check\n`in` | Checks if the $data entry is one of the validation values (as strings) | the desired values separated by `;`\n`lw_eq_th` | Checks if the $data entry is lower or equal than the validation value (as floats) | the number representing the ceiling for the check\n`lw_th` | Checks if the $data entry is lower than the validation value (as floats) | the number representing the ceiling for the check\n`match` | Checks if the $data entry matches the validation value (as strings) | The value to match against\n`match_ci` | Checks if the $data entry matches (case insensitive) the validation value (as strings) | The value to match against\n`max_len` | Checks if the $data entry has a maximum length of the validation value (as integers) | the number representing the maximum length\n`min_len` | Checks if the $data entry has a minimum length of the validation value (as integers) | the number representing the minimum length\n`range` | Checks if the $data entry is between the lower and upper bounds of the validation values, including the bounds (as floats) | the lower bound followed by the upper bound, separated by `;`\n`regex` | Checks if the $data entry matches the pattern given as validation value. | the pattern (ex: /^[a-z]+$/)\n`required` | Checks if the $data entry exists and is not an empty string | none\n\n\u003cbr\u003e\n#### =\u003e Example:  \n\nGiven the inputs:  \n\n```\n$data = [\n\t\"user_name\" =\u003e \"Pedro Henriques\",\n\t\"email\" =\u003e \"pedro@pedrojhenriques.com\",\n\t\"password\" =\u003e \"pw123\",\n\t\"password_conf\" =\u003e \"pw456\",\n\t\"gender\" =\u003e \"male\",\n\t\"commission\" =\u003e \"200\",\n\t\"planet\" =\u003e \"Mars\"\n];\n```\n\nand the validations:  \n\n```\n$validations = [\n\t\"user_name;User Name\" =\u003e [\"required\", \"max_len;50\"],\n\t\"email;Email\" =\u003e [\"required\", \"email\"],\n\t\"password;Password\" =\u003e [\"required\", \"min_len;6\", \"max_len;50\"],\n\t\"password_conf;Password Confirmation\" =\u003e [\"match;%password%\"],\n\t\"gender;Gender\" =\u003e [\"in;male;female\"],\n\t\"commission;Commission\" =\u003e [\"required\", \"range;0;100\"],\n\t\"planet;Planet of Origin\" =\u003e [\"required\", \"match;Earth\"],\n];\n```\n\nthe following errors will be generated:  \n\n```\nArray\n(\n    [password] =\u003e Array\n        (\n            [0] =\u003e The length of the Password provided is too short.\n        )\n\n    [password_conf] =\u003e Array\n        (\n            [0] =\u003e The Password Confirmation provided doesn't match Password.\n        )\n\n    [commission] =\u003e Array\n        (\n            [0] =\u003e The value provided for the Commission field must be between 0 and 100.\n        )\n\n    [planet] =\u003e Array\n        (\n            [0] =\u003e The Planet of Origin provided doesn't match Earth.\n        )\n\n)\n```\n\n\u003cbr\u003e\n#### =\u003e Available Methods:  \n\nAssuming `$validator` contains an instance of the DataValidator class.  \n\nThe following methods allow for the execution of the validations and access to their results:  \n\n\u003cbr\u003e\n=\u003e **Basic Methods**\n\nMethod | Description | Parameters | Use\n--- | --- | --- | ---\nvalidate | Executes all the validations and creates any error messages | array with the values to validate\u003cbr\u003e\u003cbr\u003earray with the validation configuration\u003cbr\u003e\u003cbr\u003eboolean controlling whether 1 failed check stops the rest from being executed, for each field | `$validator-\u003evalidate($data, $validations[, $single_fail]);`\u003cbr\u003e\u003cbr\u003eFor further details, consult the topic **Using the Data Validator** above\npassed | Returns `True` if all validations for all fields passed and `False` if at least 1 validation failed. | none | `$validator-\u003epassed();`\nfailed | Returns `True` if at least 1 validation failed and `False` if all validations for all fields passed. | none | `$validator-\u003efailed();`\ngetErrors | Returns the requested error(s) message(s). | string with the field name\u003cbr\u003e\u003cbr\u003einteger with the error index | `$validator-\u003egetErrors([string $field, integer $index]);`\u003cbr\u003e\u003cbr\u003eIf just field is provided, then all errors for that field will be returned.\u003cbr\u003eIf no parameters are provided, then all errors for all fields will be returned.\n\n\u003cbr\u003e\n=\u003e **Advanced Methods**  \n\n**NOTE:** These methods are used to customize the Data Validator. For further detail consult the topic **Customizing the Data Validator** below.\n\nMethod | Description | Parameters | Use\n--- | --- | --- | ---\naddValidation | Registers a temporary validation | string with the check type\u003cbr\u003e\u003cbr\u003efunction with the validation code | `$validator-\u003eaddValidation(string $check_type, callable $function)`\naddShortCircuit | Registers a new short-circuit rule | string with the check\u003cbr\u003e\u003cbr\u003earray with the relevant $input values\u003cbr\u003e\u003cbr\u003eboolean to flag if the check should be executed | `$validator-\u003eaddShortCircuit(string $check, array $input_values, boolean $run_check)`\naddMessage | Registers an error message | string with the message\u003cbr\u003e\u003cbr\u003estring with the check type for this message\u003cbr\u003e\u003cbr\u003estring with the field name for this message| `$validator-\u003eaddMessage(string $message, string $check_type[, string $field])`\u003cbr\u003e\u003cbr\u003eIf $field is not provided, the error message will be applied to the provided check type for all fields.\ngetDebugErrors | Returns an array with any debug messages generated after calling `validate()` | none | `$validator-\u003egetDebugErrors();`\u003cbr\u003e\u003cbr\u003eThese include any validation classes not found, invalid syntax for the `$validations` array, among others.\n\n\u003cbr\u003e\n## Customizing the Data Validator\n\nIt's possible to customize the validations as well as the error messages in 2 ways:  \n\n1. **Persistent**: Adding a new validation as a `class` and an error message as an entry in the `error_msg.json` file.\n2. **Temporary**: Registering a new validation as a temporary `function` and an error message as a temporary `string`.\n\n\u003cbr\u003e\n### Validations:\n\nWhen a validation is called, the code will first look for a temporary function with the same check type. If no matching function can be found the code will look for a defined class with a matching name (see below for naming convention).  \nThis means that custom temporary validations will have priority over the persistent validations. If you wish to change the behavior of a persistent validation, register a temporary function with the same check type.  \n\n\u003cbr\u003e\n- **Classes:**  \n\tIn regards to persistent validations, in the form of classes, the code expects the class to be named according to the following naming convention: `ValCheckType`.  \n\tAll class names start with `Val`, followed by the check type in camel case style.  \n\tIn check type, an underscore will be treated as the word separator.  \n\n\tThese classes should implement the interface `iValidation`, located at `src/interfaces/interfaces.php`.  \n\n\t**NOTE:** The code expects a validation class to belong in the **DataValidator\\Validations** namespace.\n\n\tAs an example:  \n\t```\n\tnamespace DataValidator\\Validations;\n\n\tuse DataValidator\\Interfaces\\iValidation;\n\n\tclass ValMyClass implements iValidation {\n\t\tpublic function runCheck($field, $input, array $params) {\n\t\t\t// validation code goes here!\n\t\t\t// return True if the validation passed or False if it failed.\n\t\t}\n\t}\n\t```  \n\n\tThe code will automatically look for, and include, a file with the same name as the validation class in the directory `src/validations`.  \n\tHowever, as long as the classes are defined by the time the code calls them, they don't need to be in a file with the same name, or in the default directory.  \n\n\t**EX:**  \n\tFor a check type called `min_len` the code expects a class named `ValMinLen` and will automatically look for and include a file named `ValMinLen.php`.  \n\tFor a check type called `required` the code expects a class named `ValRequired` and will look for a file named `ValRequired.php`.  \n\n\u003cbr\u003e\n- **Functions:**  \n\tIn regards to temporary validations, in the form of functions, they must be registered with the Data Validator before becoming available.  \n\tIn order to register a validation function use the method `addValidation`, listed above as an advanced method.  \n\n\tThe `$check_type` parameter must exactly match the check type provided in the `$validations` array of the `DataValidator` class' constructor.  \n\n\tThe `$function` parameter must be a function that returns `True` if the check passed or `False` if it failed.  \n\tThe function will be given the same parameters as the `runCheck()` method of the `iValidation` interface, located at `src/interfaces/interfaces.php`, so in order to have access to that information inside this function those parameters must be defined in the function's declaration.  \n\tThe function can be lambda/anonymous or \"named\".  \n\n\t**EX:**  \n\tThe following code will register a new temporary validation, accessible as check type `custom_val`:  \n\t```\n\t$validator-\u003eaddValidation(\"custom_val\", function($field, $input, array $params) {\n\t\t// validation code goes here!\n\t\t// return True if the validation passed or False if it failed.\n\t});\n\t```\n\n\u003cbr\u003e\n- **Information available for the validation:**  \n\tWhen a validation is executed, either by calling the `runCheck` method of the validation class or by running the temporary `$function`, the following parameters are given to them:  \n\n\t- `$field`: String with the name of the $data entry being validated.\u003cbr\u003e\u003cbr\u003e\n\t- `$input`: String with the value of the $data entry being validated. If `$field` doesn't exist in `$data`, then `$input` will be `null`.\u003cbr\u003e\u003cbr\u003e\n\t- `$params`: Array with all validation values provided in the `$validations` array (zero-based indexed).  \n\n\u003cbr\u003e\n**Examples:**  \n\nGiven the following code:  \n```\n$data = [\n\t\"commission\" =\u003e \"20\",\n\t\"tax\" =\u003e \"25\"\n];\n\n$validations = [\n\t\"commission;Commission Perc.\" =\u003e [\"custom_val;10;100;47\"],\n\t\"tax;Tax Perc.\" =\u003e [\"match;%commission%\"]\n];\n```\n\nThe information available to the validation method/function is:  \n\n- For `$data[\"commission\"]` and check type `custom_val`:\n\t\u003cbr\u003e\n\t- `$field`: `\"commission\"`\u003cbr\u003e\u003cbr\u003e\n\t- `$input`: `\"20\"`\u003cbr\u003e\u003cbr\u003e\n\t- `$params`: `[0 =\u003e \"0\", 1 =\u003e \"100\", 2 =\u003e \"47\"]`\n\n\u003cbr\u003e\n- For `$data[\"tax\"]` and check type `match`:\n\t\u003cbr\u003e\n\t- `$field`: `\"tax\"`\u003cbr\u003e\u003cbr\u003e\n\t- `$input`: `\"25\"`\u003cbr\u003e\u003cbr\u003e\n\t- `$params`: `[0 =\u003e \"20\"]`  -- Here `%commission%` was replaced by the commission's input\n\n\u003cbr\u003e\n### Error Messages:\n\nWhen an error message is generated, the code will first look for a temporary string with the same check type and field. If no matching string can be found the code will look for the persistent message with a matching name.  \nThis means that custom temporary strings will have priority over the persistent messages. If you wish to change the content of a persistent message, register a temporary string with the same check type.  \n\n\u003cbr\u003e\n- **\"error_msg.json\":**  \n\tIn regards to persistent messages, they must be stored in the `error_msg.json`, located by default at `src/data/error_msg.json`.  \n\tThe keys should exactly match the check types provided in the `$validations` and the values should be their respective error messages.\n\n\u003cbr\u003e\n- **Temporary String:**  \n\tIn regards to temporary messages, they must be registered with the Data Validator before becoming available.  \n\tIn order to register a temporary message use the method `addMessage`, listed above as an advanced method.  \n\n\tThe `$check_type` parameter must exactly match the check type provided in the `$validations` array of the `DataValidator` class' constructor.\n\n\u003cbr\u003e\n- **Information available for dynamic error messages:**  \n\tThe following special keywords can be used in the error message string allowing for dynamic messages:  \n\n\t- `%field%`: Will be replaced by the name of the field were the error occurred.  \n\t\tWill use the field's alias, if one was provided.\u003cbr\u003e\u003cbr\u003e\n\t- `%check_type%`: Will be replaced by the check type were the error occurred.\u003cbr\u003e\u003cbr\u003e\n\t- `%input%`: Will be replaced by the $data value being validated that generated the error.\u003cbr\u003e\u003cbr\u003e\n\t- `%params[key]%`: Will be replaced by the actual validation value in use with the given \"key\"\u003cbr\u003e\u003cbr\u003e\n\t- `%%key%%`: Will be replaced by the value in $validations with the given \"key\"  \n\t\tIf the value was another field, it's alias will be used, if one was provided.\u003cbr\u003e\u003cbr\u003e\n\n\t**NOTE:** If \"key\" is `...`, then all available values for the failed validation will be displayed, separated by `, `\n\n\u003cbr\u003e\n**Examples:**  \n\nGiven the following code:  \n```\n$data = [\n\t\"commission\" =\u003e \"20\",\n\t\"tax\" =\u003e \"25\"\n];\n\n$validations = [\n\t\"commission;Commission Perc.\" =\u003e [\"custom_val;10;100;47\"],\n\t\"tax;Tax Perc.\" =\u003e [\"match;%commission%\"]\n];\n```\n\nThe information available to the error messages is:  \n\n- For `$data[\"commission\"]` and check type `custom_val`:\n\t\u003cbr\u003e\n\t- `%field%`: `Commission Perc.`\u003cbr\u003e\u003cbr\u003e\n\t- `%check_type%`: `custom_val`\u003cbr\u003e\u003cbr\u003e\n\t- `%input%`: `20`\u003cbr\u003e\u003cbr\u003e\n\t- `%params[0]%`: `10`\u003cbr\u003e\u003cbr\u003e\n\t- `%params[1]%`: `100`\u003cbr\u003e\u003cbr\u003e\n\t- `%params[2]%`: `47`\u003cbr\u003e\u003cbr\u003e\n\t- `%params[...]%`: `10, 100, 47`\u003cbr\u003e\u003cbr\u003e\n\t- `%%0%%`: `10`\u003cbr\u003e\u003cbr\u003e\n\t- `%%1%%`: `100`\u003cbr\u003e\u003cbr\u003e\n\t- `%%2%%`: `47`\u003cbr\u003e\u003cbr\u003e\n\t- `%%...%%`: `10, 100, 47`\n\n\u003cbr\u003e\n- For `$data[\"tax\"]` and check type `match`:\n\t\u003cbr\u003e\n\t- `%field%`: `tax`\u003cbr\u003e\u003cbr\u003e\n\t- `%check_type%`: `match`\u003cbr\u003e\u003cbr\u003e\n\t- `%input%`: `25`\u003cbr\u003e\u003cbr\u003e\n\t- `%params[0]%`: `20`\u003cbr\u003e\u003cbr\u003e\n\t- `%params[...]%`: `20`\u003cbr\u003e\u003cbr\u003e\n\t- `%%0%%`: `Commission Perc.`\u003cbr\u003e\u003cbr\u003e\n\t- `%%...%%`: `Commission Perc.`\n\n\u003cbr\u003e\n### Short-Circuit Rules:\n\nIt's possible to configure certain combinations of check types and input values that will \"short-circuit\" the rest of the validations, preventing them from being executed.  \n\nIn order to register a temporary short-circuit rule use the method addShortCircuit, listed above as an advanced method.\n\nThe permanent short-circuit combinations are defined in the `$short_circuit_rules` variable, located at the start of the `DataValidator` class' definition.  \n\nBy default this variable has the following value:  \n```\n$short_circuit_rules = [\n\t[\"check\" =\u003e \"required\", \"input\" =\u003e [null, \"\"], \"run_check\" =\u003e true],\n\t[\"check\" =\u003e \"!required\", \"input\" =\u003e [null, \"\"], \"run_check\" =\u003e false]\n];\n```  \n\nThe first entry reads as follows: **\"if the field being validated has the `required` check and the $data entry is either `null` or `\"\"`, then execute the `required` check but no others.\"**  \nThis prevents multiple error messages from being generated and checks being executed unnecessarily since there is no input value to validate and one was required.  \nNote that by still executing the `required` check, which will fail, there will still be an error message being generated for that check.  \n\nThe second entry reads as follows: **\"if the field being validated doesn't have the `required` check and the $data entry is either `null` or `\"\"`, then don't execute the `required` check or any other checks.\"**  \nThis prevents an optional field that was left empty from being validated and potentially generating error messages, when no validation is required.  \nHowever, if the field was provided (`$input` will be a non empty string) then any relevant checks will be executed.  \nNote that an `!` is used to denote the absence of a check.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpedrohenriques%2Fphp_datavalidator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpedrohenriques%2Fphp_datavalidator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpedrohenriques%2Fphp_datavalidator/lists"}