{"id":18772442,"url":"https://github.com/eftec/validationone","last_synced_at":"2025-04-13T08:31:34.264Z","repository":{"id":56975561,"uuid":"151015180","full_name":"EFTEC/ValidationOne","owner":"EFTEC","description":"It is a library","archived":false,"fork":false,"pushed_at":"2024-03-02T15:09:50.000Z","size":388,"stargazers_count":10,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-13T21:29:31.598Z","etag":null,"topics":["messageitem","messagelist","php","php-library"],"latest_commit_sha":null,"homepage":"https://www.eftec.cl","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/EFTEC.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":"2018-09-30T23:13:24.000Z","updated_at":"2024-09-23T21:03:47.000Z","dependencies_parsed_at":"2023-02-15T00:31:09.056Z","dependency_job_id":null,"html_url":"https://github.com/EFTEC/ValidationOne","commit_stats":null,"previous_names":[],"tags_count":42,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EFTEC%2FValidationOne","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EFTEC%2FValidationOne/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EFTEC%2FValidationOne/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EFTEC%2FValidationOne/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/EFTEC","download_url":"https://codeload.github.com/EFTEC/ValidationOne/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223576426,"owners_count":17167866,"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":["messageitem","messagelist","php","php-library"],"created_at":"2024-11-07T19:29:08.870Z","updated_at":"2025-04-13T08:31:34.246Z","avatar_url":"https://github.com/EFTEC.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ValidationOne\r\nIt's a PHP library for fetches and validate fields and store messages in different containers(including error, warning, info\r\n, and success) depending on the conditions.\r\n\r\nThe ideology behind this library is simple: 3 classes, a simple dependencies and runs in PHP 7.1 and higher, so it could run\r\nin practically any PHP project, including WordPress, Laravel, core PHP project, etc. \r\n\r\n\r\n[![Packagist](https://img.shields.io/packagist/v/eftec/validationone.svg)](https://packagist.org/packages/eftec/ValidationOne)\r\n[![Total Downloads](https://poser.pugx.org/eftec/validationone/downloads)](https://packagist.org/packages/eftec/ValidationOne)\r\n[![Maintenance](https://img.shields.io/maintenance/yes/2025.svg)]()\r\n[![composer](https://img.shields.io/badge/composer-%3E2.0-blue.svg)]()\r\n[![php](https://img.shields.io/badge/php-7.4-green.svg)]()\r\n[![php](https://img.shields.io/badge/php-8.4-green.svg)]()\r\n[![CocoaPods](https://img.shields.io/badge/docs-70%25-yellow.svg)]()\r\n\r\n\r\n## Full Diagram\r\n\r\n![diagram full](examples/docs/diagram2022.png)\r\n\r\n## Table of contents\r\n\r\n\u003c!-- TOC --\u003e\r\n* [ValidationOne](#validationone)\r\n  * [Full Diagram](#full-diagram)\r\n  * [Table of contents](#table-of-contents)\r\n  * [Examples](#examples)\r\n  * [Concept](#concept)\r\n  * [Starting the chain](#starting-the-chain)\r\n  * [Adding a new condition](#adding-a-new-condition)\r\n    * [types](#types)\r\n    * [Type of conditions per type of input.](#type-of-conditions-per-type-of-input)\r\n    * [Types of Conditions.](#types-of-conditions)\r\n    * [Calling a custom function](#calling-a-custom-function)\r\n  * [Getting the messages](#getting-the-messages)\r\n  * [How to manage to the messages?](#how-to-manage-to-the-messages)\r\n  * [Working with dates](#working-with-dates)\r\n    * [setDateFormat](#setdateformat)\r\n    * [setDateFormatDefault](#setdateformatdefault)\r\n    * [setDateFormatEnglish](#setdateformatenglish)\r\n  * [Generating exceptions](#generating-exceptions)\r\n    * [throwOnError()](#throwonerror--)\r\n  * [Dealing with missing or empty values](#dealing-with-missing-or-empty-values)\r\n    * [exist](#exist)\r\n    * [required](#required)\r\n    * [notnull](#notnull)\r\n    * [notempty](#notempty)\r\n  * [Allowing missing or empty values](#allowing-missing-or-empty-values)\r\n  * [Processing the result](#processing-the-result)\r\n    * [def()](#def--)\r\n    * [trim()](#trim--)\r\n    * [alwaysTrim()](#alwaystrim--)\r\n    * [convert()](#convert--)\r\n  * [Version list](#version-list)\r\n  * [todo](#todo)\r\n  * [Note](#note)\r\n\u003c!-- TOC --\u003e\r\n\r\n## Examples\r\n\r\n[Examples](https://github.com/EFTEC/ValidationOne/tree/master/examples)\r\n\r\n[Tutorial Form and Table with PHP](https://github.com/EFTEC/BladeOne-tutorial1)\r\n\r\n![diagram example](examples/docs/DiagramExample.jpg)  \r\nIt is an example of functionality. A typical example is more complex, even if it's only a few lines of code.\r\n\r\n\r\n## Concept\r\n\r\nLet's say we want to validate a value an input value (get) called \"id\", we could do the next things:\r\n\r\n* The default value is the text \"**ERROR**\"\r\n* the type of the value is an **integer**, so it just returns an integer.   It also could be an integer, decimal, string, date,datestring and boolean\r\n* we add a condition, the value must be equals (**eq**) to **10**. If it fails, then it returns a message (as **error**)\r\n* we add another condition if the value must be equals (**eq**) to **30**. If it fails, then it returns an **info** (not an error)\r\n* If the operation fails, then it returns the default value.\r\n* And finally, we obtain the \"**id**\" from $_GET (parameter URL).\r\n\r\n```php\r\nuse eftec\\ValidationOne;\r\n$val=new ValidationOne();\r\n\r\n$r = $val-\u003edef('ERROR')\r\n    -\u003etype('integer')\r\n    -\u003eifMissingThenDefault()\r\n    -\u003econdition(\"eq\", \"It's not equals to 10\", 10)\r\n    -\u003econdition(\"eq\", \"It's not equals to 30 (info)\", 30, 'info')\r\n    -\u003eifFailThenDefault()\r\n    -\u003eget('id'); // \u003c-- end of the chain\r\n\r\n```\r\n\r\nBut where is the error?.  The messages are stored in **messageList**\r\n\r\n```php\r\nvar_dump($val-\u003emessageList-\u003eallArray()); // here we show all messages of any kind of type. \r\nvar_dump($val-\u003emessageList-\u003eerrorCount); // returns the number of errors.\r\nvar_dump($val-\u003eerrorcount()); // returns the number of errors (alternative)\r\nvar_dump($val-\u003ehasError()); // returns true if there is an error.\r\n```\r\nHowever, we could also show a message by type (error, warning..) and only message by a specific identifier.\r\n\r\n```php\r\nvar_dump($val-\u003emessageList-\u003eget('id')-\u003eallErrorOrWarning()); // All error or warning contained in the key \"id\".\r\n```\r\n\r\nWhy the messages are store in some structure?. Is it not easy to simply return the error?\r\n\r\nAn answer is a form. Let's say we have a form with three fields. If one of them fails, then the error must be visible for each field separately.  Also, the whole form could have its own message.\r\n\r\n## Starting the chain\r\n\r\nThe start of the chain usually it is written at the end of the code.\r\n\r\nThe methods allowed are:\r\n\r\n* get(): it reads a value from $_GET\r\n* post(): it reads a value from $_POST\r\n* request():  It reads a value from $_REQUEST\r\n* getFile(). It reads a value from$_FILES\r\n* set(): it reads a value entered manually (a variable or constant)\r\n\r\nExample:\r\n\r\n```php\r\n$val=new ValidationOne();\r\n$id = $val-\u003etype('integer')-\u003eget('id'); \r\n$id = $val-\u003etype('integer')-\u003epost('id');\r\n$id = $val-\u003etype('integer')-\u003erequest('id');\r\n$id = $val-\u003etype('integer')-\u003eset('123','id');\r\n\r\n$val=new ValidationOne();\r\n$id = $val-\u003etype('integer')-\u003eget('id'); // $_GET['id']\r\n$val=new ValidationOne('frm'); // we set a prefix for every reading.\r\n$id = $val-\u003etype('integer')-\u003eget('id'); // $_GET['frm_id']\r\n```\r\n\r\n\r\n\r\n## Adding a new condition \r\n\r\n\u003e condition ($condition, $message = \"\", $conditionValue = null, $level = 'error', $key = null)\r\n\r\nIt adds a condition that it depends on the **type** of the input.\r\n\r\n* @param string $condition\r\n\r\n\t\u003cb\u003enumber\u003c/b\u003e:req,eq,ne,gt,lt,gte,lte,between,null,notnull\u003cbr\u003e\r\n\t\u003cb\u003estring\u003c/b\u003e:req,eq,ne,minlen,maxlen,betweenlen,null,notnull,contain,notcontain\r\n\t,alpha,alphanum,text,regexp,email,url,domain\u003cbr\u003e\r\n\t\u003cb\u003edate\u003c/b\u003e:req,eq,ne,gt,lt,gte,lte,between\u003cbr\u003e\r\n\t\u003cb\u003edatestring\u003c/b\u003e:req,eq,ne,gt,lt,gte,lte,between\u003cbr\u003e\r\n\t\u003cb\u003eboolean\u003c/b\u003e:req,eq,ne,true,false\u003cbr\u003e\r\n\t\u003cb\u003efile\u003c/b\u003e:minsize,maxsize,req,image,doc,compression,architecture,ext\u003cbr\u003e\r\n\t\u003cb\u003efunction:\u003c/b\u003e\u003cbr\u003e\r\n\tfn.static.Class.methodstatic\u003cbr\u003e\r\n\tfn.global.function\u003cbr\u003e\r\n\tfn.object.Class.method where object is a global $object\u003cbr\u003e\r\n\tfn.class.Class.method\u003cbr\u003e\r\n\tfn.class.\\namespace\\Class.method\u003cbr\u003e\r\n\t\r\n* @param string $message  \r\n\r\n    Message could use the next variables '%field','%realfield','%value','%comp','%first','%second'  \r\n\r\n| Field      | Description                                                        | Example             |\r\n|------------|--------------------------------------------------------------------|---------------------|\r\n| %field     | name of the field, it could be the **friendid** or the actual name | CustomerID          |\r\n| %realfield | name of the field (not the  **friendid**)                          | Customer Identifier |\r\n| %value     | current value of the field                                         | John                |\r\n| %comp      | value to compare (if any)                                          |                     |\r\n| %first     | first value to compare (if the compare value  is an array)         |                     |\r\n| %second    | second value to compare (if the compare  value is an array)        |                     |\r\n| %key       | key used (for input array)                                         |                     |\r\n\r\n* @param null $conditionValue\r\n\r\n* @param string $level (error,warning,info,success). The level of the error. See **MessageContainer** for further information\r\n\r\n* @param string $key If the key is not null then it is used to add more than one condition by key\r\n\r\n* @return ValidationOne\r\n\r\n\u003e Note: if the value is null and isNullValid() is true, then the conditions are ignored.\r\n\u003e If the value is missing and isMissingValid() is true, then the conditions are ignored.\r\n\u003e If the value is empty ('') and isEmptyValid() is true, then the conditions are ignored.\r\n\u003e If the value is empty ('') or null and isNullOrEmptyValid() is true, then the conditions are ignored.\r\n\u003e isNullValid(),isMissingValid(),isNullOrEmptyValid() and isEmptyValid() are useful when we want to validate a value \r\n\u003e only if it exists or if the value is set.\r\n\r\nExample:\r\n\r\n```php\r\n$validation-\u003edef(null)\r\n    -\u003etype('integer')\r\n    -\u003econdition('eq','%field %value is not equal to %comp ',50)\r\n    -\u003econdition('eq','%field %value is not equal to %comp ',60)\r\n    -\u003eset('aaa','variable2');\t\r\n```\r\n\r\n### types\r\n\r\n| type           | description                                                                                             |\r\n|----------------|---------------------------------------------------------------------------------------------------------|\r\n| integer        | (numeric) it allows a number without decimal                                                            |\r\n| unixtime       | (numeric) it allows a number without decimal                                                            |\r\n| boolean        | (boolean) it stores true or false. The input could vary (empty, zero or   null = false, otherwise true) |\r\n| decimal        | (numeric) it allows a number with decimal                                                               |\r\n| float          | (numeric) it allows a number with decimal                                                               |\r\n| varchar        | (string) it allows any input                                                                            |\r\n| string         | (string) it allows any input                                                                            |\r\n| date           | (date) the input could be a DateTime or a string. The value is stored as   an object DateTime           |\r\n| datetime       | (date) the input could be a DateTime or a string. The value is stored as   an object DateTime           |\r\n| datestring     | (date) the input could be a DateTime or a string. The value is stored as a string                       |\r\n| datetimestring | (date) the input could be a DateTime or a string. The value is stored as a string                       |\r\n| file           | (file) the input is a string, and it's store as a string, but it adds special validation                |\r\n\r\n\r\n\r\n### Type of conditions per type of input.\r\n\r\n| Input type                   | Condition                                                                                   |     |\r\n|------------------------------|---------------------------------------------------------------------------------------------|-----|\r\n| number                       | gt,lt,gte,lte,between                                                                       |     |\r\n| string                       | minlen,maxlen,betweenlen,contain\u003cbr\u003e,notcontain,alpha,alphanum,text,regexp,email,url,domain |     |\r\n| date                         | gt,lt,gte,lte,between                                                                       |     |\r\n| datestring                   | gt,lt,gte,lte,between                                                                       |     |\r\n| boolean                      | true,false                                                                                  |     |\r\n| file                         | minsize,maxsize,req,image,doc,compression,architecture,ext                                  |     |\r\n| *  (it applies for any type) | req,eq,ne,null,notnull,empty,notempty                                                       |     |\r\n| *                            | function                                                                                    |     |\r\n| *                            | fn.static.Class.methodstatic                                                                |     |\r\n| *                            | fn.global.function                                                                          |     |\r\n| *                            | fn.object.Class.method where object is a global $object                                     |     |\r\n| *                            | fn.class.Class.method                                                                       |     |\r\n| *                            | fn.class.\\namespace\\Class.method                                                            |     |\r\n\r\n### Types of Conditions.\r\n\r\n| Condition                                                        | Description                                                                      | Value Example                                              |\r\n|------------------------------------------------------------------|----------------------------------------------------------------------------------|------------------------------------------------------------|\r\n| architecture                                                     | The extension of the file must be an architecture file (dwg, etc.)               |                                                            |\r\n| between                                                          | The number must be between two values                                            | [0,20]                                                     |\r\n| betweenlen                                                       | The length of the text must be between two values                                | [0,20]                                                     |\r\n| compression                                                      | The extension of the file must be an compression file                            |                                                            |\r\n| contain                                                          | The text must contain a value                                                    | \"text\"                                                     |\r\n| doc                                                              | The extension of the file must be a document file                                |                                                            |\r\n| eq (it could be an array or value) / ==                          | The value must be equals to\u003cbr /\u003eThe value must be contained in a array          | \"text\",[\"text\",\"text2\"]                                    |\r\n| exist                                                            | The file or value must exist (it could be null/empty)                            |                                                            |\r\n| missing / notexist                                               | The file or value must not exists or be null/empty                               |                                                            |\r\n| required (or req)                                                | The value must not be null or empty                                              |                                                            |\r\n| ext                                                              | The extension (file) must be in the list of extensions                           | [\"ext1\",\"ext2\",\"ext3\"]                                     |\r\n| false                                                            | The value must be false (===false)                                               |                                                            |\r\n| fn.class.\\namespace\\Class.method                                 | The method of a class must returns true                                          |                                                            |\r\n| fn.class.Class.method                                            | The method of a class must returns true                                          |                                                            |\r\n| fn.global.function                                               | The global function must returns true                                            |                                                            |\r\n| fn.object.Class.method where object is a global $object          | The method of a global object must returns true                                  |                                                            |\r\n| fn.static.Class.methodstatic                                     | The static method of a class must returns true                                   |                                                            |\r\n| function                                                         | The function must returns true                                                   |                                                            |\r\n| gt / \u003e                                                           | The value must be greater than                                                   | 123                                                        |\r\n| gte  / \u003e=                                                        | The value must be greater or equal than                                          | 123                                                        |\r\n| image                                                            | The extension of the file must be an image file                                  |                                                            |\r\n| lt  / \u003c                                                          | The value must be less than                                                      | 123                                                        |\r\n| lte / \u003c=                                                         | The value must be less or equal than                                             | 123                                                        |\r\n| maxlen                                                           | The maximum length of a string                                                   | 123                                                        |\r\n| maxsize                                                          | The maximum size of a file                                                       | 123                                                        |\r\n| minlen                                                           | The minimum length of a string                                                   | 123                                                        |\r\n| minsize                                                          | The minimum size of a file                                                       | 123                                                        |\r\n| mime (the value to compare could be an string or array)          | The mime type of a file                                                          | \"application/msword\" or [\"application/msword\",\"image/gif\"] |\r\n| mimetype                                                         | The mime type (without subtype) of a file                                        | \"application\" or [\"application,\"image\"]                    |\r\n| ne / != (the value to compare could be an single value or array) | The value must not be equals.\u003cbr /\u003eOr the value must not be contained in a array | 123,[123,345],[\"aa\",\"bb\"]                                  |\r\n| notcontain                                                       | The value must not contain a value                                               | \"text\"                                                     |\r\n| notnull                                                          | The value must not be null                                                       |                                                            |\r\n| null                                                             | The value must be null                                                           |                                                            |\r\n| empty                                                            | The value must be empty (i.e. \"\",0,null)                                         |                                                            |\r\n| notempty                                                         | The value must not be empty (i.e. not equals to \"\",0,null)                       |                                                            |\r\n| req                                                              | The value must exists                                                            |                                                            |\r\n| true                                                             | The value must be true (===true)                                                 |                                                            |\r\n\r\n\r\nExamples:\r\n\r\n```php\r\n$validation-\u003edef(null)\r\n    -\u003etype('integer')\r\n    -\u003econdition('eq','%field %value is not equal to %comp ',50)\r\n    -\u003econdition('between','%field %value must be between 1 and 50 ',[1,50])\r\n    -\u003econdition('eq','%field %value is not equal to %comp ',60)\r\n    -\u003econdition('eq','%field %value is not equal to %comp ',[60,200]) // eq allows a single or array\r\n    -\u003econdition('fn.static.Example.customval','the function does not work')\r\n    -\u003econdition('req')\r\n    -\u003econdition('lt',\"es muy grande\",2000,'warning')\r\n    -\u003econdition('eq','%field %value is not equal to %comp',50)\r\n    -\u003econdition('fn.static.Example.fnstatic','the static function does not work')\r\n    -\u003econdition('fn.static.\\somespace\\Someclass.methodStatic',null)\r\n    -\u003econdition('fn.global.customval','The global function does not work')\r\n    -\u003econdition('fn.object.example.fnnostatic','the function object does not work')\r\n    -\u003econdition('fn.class.\\somespace\\Someclass.method','The function some class does not work')\r\n    -\u003econdition('fn.class.Example.fnnostatic','la funcion class no funciona');\r\n\r\n// -\u003econdition('fn.static.Example.customval','la funcion no funciona') \r\nfunction customval($value,$compareValue) {\r\n    return true;\r\n}\r\n```\r\n### Calling a custom function\r\n\r\nSometimes we need to use a custom condition. We could create a global variable, a static function, or even a method \r\ninside a class.  \r\nEvery method or function created must have two parameters (with any name): \r\n* **$value** The value to evaluate.\r\n* **$compareValue** The value to compare (it could be optional)\r\n\r\nFor example, what if we need to evaluate if some id does not exist in the Database?\r\n\r\n```php\r\n$validation-\u003econdition('fn.global.idExist','The id already exist!')-\u003eget(\"id\"); \r\n\r\nfunction idExist($id,$compare=null) {\r\n   // select count(*) c from table where id=$id\r\n   if($c\u003e0) {\r\n        return true; \r\n   } else {\r\n        return false;\r\n   }   \r\n}\r\n\r\n```\r\n\r\n\r\n\u003e Note: if we need to specify a namespace, then we could use the notation: \\namespace\\SomeClass\r\n\r\n```php\r\n$validation-\u003econdition('fn.global.customfn'); // global\r\n$validation-\u003econdition('fn.static.SomeClass.staticfn'); // calling a static method inside the class SomeClass.\r\n$validation-\u003econdition('fn.class.SomeClass.noStaticFn'); // method inside a class,it creates an instance of an object then it calls the method\r\n$validation-\u003econdition('fn.object.myObject.noStaticFn'); // method inside a class, it uses an instance called $myObject\r\n\r\n// global function\r\nfunction customfn($value,$compareValue) {\r\n    // returns true or false\r\n}\r\n// static function\r\n$myObject=new SomeClass();\r\nclass SomeClass {\r\n    public static function staticfn($value,$compareValue) {\r\n        // returns true or false\r\n    }\r\n    public function noStaticFn($value,$compareValue) {\r\n        // returns true or false\r\n    }\r\n}\r\n\r\n```\r\n\r\n## Getting the messages\r\n\r\nWhen we validate an object, it could store the information inside the Message Container (also called Message List).\r\n\r\n**MessageContainer** ([EFTEC/MessageContainer](https://github.com/EFTEC/MessageContainer)) contains a list \r\nmessages in a hierarchy way:\r\n\r\n```php\r\n⭐ Container (usually only 1 for all the project)\r\n     ⭐ Lockers (from zero to many)\r\n         ⭐ Messages (from zero to many and grouped by level)\r\n    \r\n$container-\u003eget('locker20')-\u003efirstError(); // it returns the first message of error in the locker20 that is part of the container.    \r\n    \r\n```\r\n\r\nMessages are leveled as follows\r\n\r\n| id      | Description                                                                                                                                      | Example                                   |\r\n|---------|--------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------|\r\n| error   | The message is an error, and it must be solved. It is our show stopper.                                                                          | Database is down                          |\r\n| warning | The message is a warning that maybe it could be ignored.  However, the class **MessageContainer** allows to group Error and Warning as the same. | The registry was stored but with warnings |\r\n| info    | The message is information. For example, to log or debug an operation.                                                                           | Log is stored                             |\r\n| success | The message is a successful operation                                                                                                            | Order Accepted                            |\r\n\r\n## How to manage to the messages?\r\n\r\n| Function                                           | Description                                                                                                                                     | Example                                                      |\r\n|----------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------|\r\n| addMessage($idLocker, $message, $level =  'error') | It adds a message inside a locker.  \u003cbr /\u003eUsually, it is done automatically by the library but you can add messages manually via code.          | $this-\u003eaddMessage('pwd','the password is required','error'); |\r\n| getMessage($withWarning = false)                   | It gets the first error message or empty if none                                                                                                | $this-\u003egetMessage();                                         |\r\n| getMessages($withWarning = false)                  | It gets all the error messages or empty if none                                                                                                 | $this-\u003egetMessages();                                        |\r\n| getMessageId($idLocker)                            | It gets a **MessageLocker** object (see [EFTEC/MessageContainer](https://github.com/EFTEC/MessageContainer#messagelocker) for more information) | $obj=$this-\u003egetMessageId('pwd');                             |\r\n| errorCount(includeWarning=false)                   | It gets the error count                                                                                                                         | $count=$this-\u003eerrorCount();                                  |\r\n| hasError($includeWarning=false)                    | It returns true if there is an error                                                                                                            | $fail=$this-\u003ehasError();                                     |\r\n\r\n\r\n\r\n| Field        | Description                                                                      | Example                        |\r\n|--------------|----------------------------------------------------------------------------------|--------------------------------|\r\n| $messageList | It gets all the container. It returns an object of the type **MessageContainer** | $container=$this-\u003emessageList; |\r\n\r\nYou can see more information about **MessageContainer** in [EFTEC/MessageContainer](https://github.com/EFTEC/MessageContainer)\r\n\r\nExample:\r\n\r\n```php\r\n$validation-\u003eaddMessage('idlocker','this field is required','error'); // it adds a message inside a locker.\r\n$validation-\u003emessageList-\u003eget('idlocker')-\u003eallError(); // it gets all errors from the locker idlocker\r\n$validation-\u003egetMessages(true); // it gets all messages of error or warning from all the lockers.\r\n\r\n```\r\n\r\n\r\n\r\n\r\n\r\n## Working with dates\r\n\r\nWe also could work with dates.  There are several types of date formats.\r\n\r\n| type           | description                                                                                                                 |\r\n|----------------|-----------------------------------------------------------------------------------------------------------------------------|\r\n| date           | (date) the input could be a DateTime or a string. The value is stored as  an object DateTime                                |\r\n| datetime       | (date) the input could be a DateTime or a string. The value is stored as  an object DateTime                                |\r\n| datestring     | (date) the input could be a DateTime or a string. The value is stored as a string using the field **$dateOutputString**     |\r\n| datetimestring | (date) the input could be a DateTime or a string. The value is stored as a string using the field **$dateLongOutputString** |\r\n\r\nThere are two ways to specify the format of dates, short (Date only) and long (date and time). And we could specify the format as input and output.\r\n\r\n| Name Field            | Description                                            | Default value  |\r\n|-----------------------|--------------------------------------------------------|----------------|\r\n| $dateShort            | It is the (expected) input format for date (short)     | d/m/Y          |\r\n| $dateLong             | It is the (expected) input format (with date and time) | d/m/Y H:i:s    |\r\n| $dateOutputString     | It is the output format (for datestring)               | Y-m-d          |\r\n| $dateLongOutputString | It is the output format (for datetimestring)           | Y-m-d\\TH:i:s\\Z |\r\n\r\n```php\r\n$r=getVal()-\u003etype('datestring')-\u003eset('31-12-2019'); // 2019-12-31 note: the default input value is d/m/Y, not m/d/Y\r\n```\r\n\r\nWe can change the date format by changing the fields or calling the next functions\r\n\r\n### setDateFormat\r\n\r\nSetting the format of the dates (input short, input long, output short and output long)\r\n\r\n```php\r\n$validation-\u003esetDateFormat('m/d/Y', 'm/d/Y H:i:s', 'Y-m-d', 'Y-m-d\\TH:i:s\\Z')\r\n```\r\n\r\n### setDateFormatDefault\r\n\r\nWe set the format of the dates to the default configuration\r\n\r\n```php\r\n$validation-\u003esetDateFormatDefault();\r\n```\r\n\r\n### setDateFormatEnglish\r\n\r\nWe set the format to the dates to :\r\n\r\n| Name         | Format         |\r\n|--------------|----------------|\r\n| input short  | m/d/Y          |\r\n| input long   | m/d/Y H:i:s    |\r\n| output short | Y-m-d          |\r\n| output long  | Y-m-d\\TH:i:s\\Z |\r\n\r\n```php\r\n$validation-\u003esetDateFormatEnglish()\r\n```\r\n\r\n## Generating exceptions\r\n\r\nBy default, this library does not generate exceptions. \r\nHowever, it is possible to generate exceptions if the message is of the type ERROR and/or WARNING.\r\n\r\n### throwOnError()\r\n\r\nWith this method, if the container generates an error, then it is stored also generates a new exception.\r\n\r\n\u003e Note: By default, most messages are of the type ERROR.\r\n\u003e\r\n\u003e Note: When the operator is throw, then the value is not assigned and the stack is deleted, i.e. if we throw an exception, all the information is lost.\r\n\r\n\r\n\r\n```php\r\ntry {\r\n    $validation-\u003etype('integer')\r\n        -\u003ethrowOnError() // for errors only\r\n        -\u003eset('hello', 'field1'); \r\n    // or you could use:\r\n    $validation-\u003etype('integer')\r\n        -\u003ethrowOnError(true,true) // for errors and warnings\r\n        -\u003eset('hello', 'field1'); \r\n    $this-\u003efail('this value means the throw failed');\r\n} catch(\\Exception $ex) {\r\n    $this-\u003eassertEquals('field1 is not numeric',$ex-\u003egetMessage());\r\n}\r\n```\r\n\r\n## Dealing with missing or empty values\r\n\r\nThere are four different ways to deal with empty values in this library.  \r\n\r\n### exist\r\n\r\n* A value **exist** if the field or file exists, no matter the value or if it is null or empty.\r\n  * if exist() is set and the value is missing, then it raise an error.\r\n\r\n\r\n```php\r\n   $validation-\u003eexist()-\u003eset(null); // is valid.\r\n   $validation-\u003eexist()-\u003eset(''); // is valid.\r\n   $validation-\u003eexist()-\u003eget('field'); // is valid only if $_GET['field'] exist (even if it is null)\r\n```\r\n\r\n### required\r\n\r\n* A value is **required** if the field is not null or empty. Required is equals that null and empty at the same time\r\n\r\n```php\r\n   $validation-\u003erequired()-\u003eset(null); // is not valid.\r\n   $validation-\u003erequired()-\u003eset(\"\"); // is not valid.\r\n   $validation-\u003erequired()-\u003eset('hi'); // is valid.   \r\n```\r\n\r\n### notnull\r\n\r\n* A value is **not null** if the field is not null, but it could be empty (\"\").\r\n\r\n```php\r\n   $validation-\u003enotnull()-\u003eset(null); // is not valid.\r\n   $validation-\u003enotnull()-\u003eset(\"\"); // is valid.\r\n   $validation-\u003enotnull()-\u003eset('hi'); // is valid.   \r\n```\r\n\r\n### notempty\r\n\r\n* A value is **not empty** if the field is not '' (string with length 0), but it could be null.\r\n\r\n```php\r\n   $validation-\u003enotempty()-\u003eset(null); // is valid.\r\n   $validation-\u003enotempty()-\u003eset(\"\"); // is not valid.\r\n   $validation-\u003enotempty()-\u003eset('hi'); // is valid.   \r\n```\r\n\r\n## Allowing missing or empty values\r\n\r\nAlso, there are 4 ways to accept missing values, null or empty, bypassing any condition.\r\n\r\n```php\r\n   $validation-\u003eisNullValid()-\u003econdition(....)-\u003eset(null); // is valid no matter the condition.\r\n   $validation-\u003eisNullorEmptyValid()-\u003econdition(....)-\u003eset(null); // is valid no matter the condition.\r\n   $validation-\u003eisEmptyValid()-\u003econdition(....)-\u003eset(''); // is valid no matter the condition.\r\n   $validation-\u003eisMissingValid()-\u003econdition(....)-\u003eget('field'); // If the field is missing, then is valid no matter the condition\r\n```\r\n\r\nIt is used when we need to validate when an input has some value unless the value is missing, empty or null. \r\n\r\n\u003e isNullorEmptyValid() is equals than to call: isEmptyValid()-\u003eisNullValid()\r\n\r\nAlso, those operators could be stacked.\r\n\r\n```php\r\n$validation\r\n    -\u003eisNullorEmptyValid()\r\n    -\u003eisMissingValid()\r\n    -\u003econdition(....)\r\n    -\u003eset(....); // this expression is valid if the value is null, empty(''), the value is missing, no matter the conditions.\r\n```\r\n\r\n## Processing the result\r\n\r\n### def()\r\n\r\nWe could set a default value. This value could be as fallback when there is an error.  The default value is never converted or processed.\r\n\r\n```php\r\n$validation\r\n    -\u003edef(-1)\r\n    -\u003etype('integer')\r\n    -\u003eifFailThenDefault() \r\n    -\u003eset(...); // if the operation fails, then it returns -1\r\n```\r\n\r\n\r\n\r\n### trim()\r\n\r\nTrim the result. By default, the result is not trimmed. You can trim the left, right or both sides. It uses the method convert() to do the operation.\r\n\r\n\r\n```php\r\n$validation-\u003etrim()-\u003eset(....); // trim both sided\r\n$validation-\u003etrim('trim','.,')-\u003eset(....); // trim . and ,\r\n$validation-\u003etrim('ltrim')-\u003eset(....); // trim left sided\r\n$validation-\u003etrim('rtrim')-\u003eset(....); // trim right sided\r\n\r\n```\r\n\r\n### alwaysTrim()\r\n\r\nSometimes, we always want to trim the results. So we could use this method to always trim the result. It stacks at the end of the conversion.\r\n\r\n```php\r\n$validation-\u003ealwaysTrim(); // always trim the next characters \" \\t\\n\\r\\0\\x0B\"\r\n$validation-\u003ealwaysTrim(true,\",.\"); // always trim , and .\r\n// ...\r\n$validation-\u003ealwaysTrim(false);  // we disable the always trim.\r\n```\r\n\r\n### isArray()\r\n\r\nIf we want to fetch an array, then we could use the next method\r\n\r\n```php\r\n$array=$validation-\u003eisArray()-\u003erequest('id');\r\n```\r\nIt also validates every value. However, it stores the messages in a single container.\r\n\r\nIf we want to store every message separately, then we could use:\r\n```php\r\n$array=$validation-\u003eisArray(true)-\u003erequest('id');\r\n```\r\n\r\n#### Example of array\r\n\r\n```html\r\n\u003cform\u003e\r\n    \u003cinput type='text' name='field[col1][0]' value=\"cocacola\" /\u003e\r\n    \u003cinput type='text' name='field[col2][0]' value=\"123\" /\u003e\u003cbr\u003e\r\n    \u003cinput type='text' name='field[col1][1]' value=\"fanta\" /\u003e\r\n    \u003cinput type='text' name='field[col2][1]' value=\"123\" /\u003e\u003cbr\u003e\r\n    \u003cinput type=\"submit\"\u003e\u003cbr\u003e\r\n\u003c/form\u003e\r\n```\r\n\r\n\u003eNote: You could also define the fields as 'field\\[0]\\[col1]' so you won't need to invert the array\r\n\r\n```php\r\n$values=getVal()-\u003eisArray(true)-\u003erequest('field'); // ['col1'=\u003e['cocacola','fanta'],'col2'=\u003e[123,123]]\r\nValidationOne::invertArray($values); // // [['col1'=\u003e'cocacola','col2'=\u003e123],['col1'=\u003e'fanta','col2'=\u003e123]]\r\n```\r\n\r\n### invertArray()\r\n\r\nIf the value is an array but the indexes of the columns are inverted with the columns, then you can invert the order\u003cbr\u003e\r\n**example:**\r\n\r\n```php\r\n$arr=['col1'=\u003e['cocacola','fanta'],'col2'=\u003e[1,2]];\r\nValidationOne::invertArray($arr); // [['col1'=\u003e'cocacola','col2'=\u003e1],['col1'=\u003e'fanta','col2'=\u003e2]]\r\n'''\r\n\r\n\r\n\r\n\r\n\r\n### convert()\r\n\r\nIt converts the end result after it is validated. Depending on the type of conversion, it allows up to 2 arguments.   The conversion could be stacked so the order could matter.\r\n\r\nIf the value is missing, or it is used the default value, then it is not converted.\r\n\r\n| Type              |     | Description                                                                                 | Example                                                                                                                                                                           |\r\n|-------------------|-----|---------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\r\n| upper             |     | Converts the value in uppercase                                                             | $this-\u003econversion('upper')-\u003eset('Hello World'); // HELLO WORLD                                                                                                                    |\r\n| lower             |     | Converts the value in lowercase                                                             | $this-\u003econversion('lower')-\u003eset('Hello World'); // hello world                                                                                                                    |\r\n| ucfirst           |     | Converts the first character in uppercase                                                   | $this-\u003econversion('ucfirst')-\u003eset('hello world'); // Hello world                                                                                                                  |\r\n| ucwords           |     | Converts the first character in a word in uppercase                                         | $this-\u003econversion('ucwords')-\u003eset('hello world'); // Hello World                                                                                                                  |\r\n| replace           |     | Replace a string by other                                                                   | $this-\u003econversion('replace','hello','world')-\u003eset('hello hello'); // world world                                                                                                  |\r\n| sanitizer         |     | Sanitizer the result. It uses filter_var()                                                  | $this-\u003econversion('sanitizer',FILTER_SANITIZE_EMAIL)-\u003eset('//aaa@bb.com'); // aaa@bb.com\u003cbr /\u003e$this-\u003econversion('sanitizer',FILTER_SANITIZE_SPECIAL_CHARS,FILTER_FLAG_STRIP_HIGH) |\r\n| alphanumeric      |     | Sanitize the result by keeping the alphanumeric characters plus underscore :                | this-\u003econversion('alphanumeric')-\u003eset('HELLO world_-123'); // HELLOworld_123                                                                                                      |\r\n| alphanumericminus |     | Sanitize the result by keeping the alphanumeric characters plus underscore and minus symbol | this-\u003econversion('alphanumericminus')-\u003eset('HELLO world_-123'); // HELLOworld_-123                                                                                                |\r\n| regexp            |     | It calls preg_replace to replace a text                                                     | this-\u003econversion('regexp','/[/^0-9]/','')-\u003eset('hello123'); // 123                                                                                                                |\r\n| rtrim             |     | Trim the right characters                                                                   | $this-\u003econversion('rtrim')                                                                                                                                                        |\r\n| ltrim             |     | Trim the left characters                                                                    | $this-\u003econversion('ltrim')                                                                                                                                                        |\r\n| trim              |     | Trim the right and left. It is equivalent to $this-\u003etrim()                                  | $this-\u003econversion('trim')-\u003eset(' hello '); // hello\u003cbr /\u003e$this-\u003econversion('trim',\" \\t\\n\\r\\0\\x0B\")                                                                                |\r\n| htmlencode        |     | Encode to html content. It uses htmlentities()                                              | $this-\u003econversion('htmlencode')-\u003eset('\\\u003cb\u003edog\\\u003c/b\u003e'); //\\\u0026lt;b\\\u0026gt;dog\\\u0026lt;                                                                                                       |\r\n| htmldecode        |     | Decode from a html. It uses html_entity_decode()                                            | $this-\u003econversion('htmldecode')-\u003eset('\\\u0026lt;b\\\u0026gt;dog\\\u0026lt;'); // \\\u003cb\u003edog\\\u003c/b\u003e                                                                                                      |\r\n\r\n\r\n\r\n```php\r\n$validation\r\n    -\u003econvert('replace','hello','world') // world world\r\n    -\u003econvert('upper') // WORLD WORLD\r\n    -\u003eset('hello hello');  // stacking an operator.\r\n\r\n$validation-\u003econvert('upper')-\u003eset(....); \r\n$validation-\u003econvert('lower')-\u003eset(....); \r\n$validation-\u003econvert('ucfirst')-\u003eset(....); \r\n$validation-\u003econvert('ucwords')-\u003eset(....); \r\n$validation-\u003econvert('replace','hello','world')-\u003eset(....); // trim right sided\r\n$validation-\u003econvert('sanitizer',FILTER_SANITIZE_EMAIL)-\u003eset(....);\r\n$validation-\u003econvert('rtrim')-\u003eset(....);\r\n$validation-\u003econvert('ltrim')-\u003eset(....);\r\n$validation-\u003econvert('trim')-\u003eset(....);\r\n$validation-\u003econvert('htmlencode')-\u003eset(....);\r\n$validation-\u003econvert('htmldecode')-\u003eset(....);\r\n\r\n```\r\n\r\n\r\n\r\n\r\n\r\n\r\n## Version list\r\n* 2024-12-31 2.10\r\n  * Updated to PHP 8.4 \r\n* 2024-03-02 2.9\r\n  * Updating dependency to PHP 7.4. The extended support of PHP 7.2 ended 3 years ago.\r\n  * Added more type hinting in the code.\r\n* 2023-11-13 2.8\r\n  * some maintenance code.   \r\n* 2023-02-26 2.7\r\n  * added a new argument for isArray()\r\n  * added the static method invertArray()\r\n* 2023-01-26 2.6\r\n  * Some small cleanups. \r\n* 2022-08-27 2.5\r\n  * **[update]** added the validation of arguments for most of the functions of the library.\r\n* 2022-03-11 2.4\r\n  * **[update]** added condition alphanumunder (alphanumeric or underscore).\r\n* 2022-02-05 2.3\r\n  * **[update]** update dependency to MessageContainer 2.3. Now MessageContainer is injected as singleton.\r\n  * **[update]** ValidationOne methods now has type hinting (return values).\r\n  * **[fix]** inputDate() method has some wrong operations. Now, they were removed.\r\n* 2022-02-04 2.2\r\n  * **[new]** support to PHP 8.1.  PHP 8.1 is quite tricky, it deprecated a lot of arguments for several functions.\r\n  * **[new]** This library support PHP 7.2 or higher. If you need older functionality, then you can use an old version.\r\n* 2022-01-29 2.1\r\n  * **[new]** method throwOnError()\r\n* 2022-01-29 2.0.2\r\n  * fixed a problem when the condition is \"gte\". \r\n* 2022-01-15 2.0.1\r\n  * Update dependency \r\n* 2022-01-15 2.0\r\n  * PHP 7.1 and higher.\r\n  * [core] Lots of cleanups\r\n* 2021-03-18 1.30.1\r\n  * Updated dependency in composer.json\r\n* 2021-03-17 1.30\r\n  * We split the library in two, one for the validation (this library) and other for the messages, called eftec/MessageContainer.\r\n* 2021-02-13 1.29\r\n  * Added the methods trim(), alwaysTrim(), convert(), errorCount() and hasError() .\r\n* 2021-02-10 1.28\r\n  * Added new method isNullOrEmptyValid()   \r\n* 2021-02-10 1.27\r\n  * Added new methods isMissingValid(), isEmptyValid() and isNulLValid()   \r\n* 2021-02-09 1.26\r\n  * New validations and methods.\r\n  * exist() where the value must exist (but it could be null or empty)\r\n  * required() now it validates if the value is not null or empty only. It does not validate if the value exists.\r\n  * notempty()\r\n* 2021-01-07 1.25\r\n    * PHP 8.0 discontinued the constants INPUT_GET, INPUT_POST and INPUT_REQUEST, so we will use instead the numbers\r\n        * INPUT_POST = 0\r\n        * INPUT_GET = 1\r\n        * INPUT_REQUEST = 99\r\n        So, if you are using INPUT_GET,INPUT_POST OR INPUT_REQUEST, then they will still work.   \r\n* 2020-10-01 1.24.3\r\n    * A small cleanup.   \r\n* 2020-05-21 1.24.2\r\n    * Fixed a problem with conditions and array (when it is initiated).    \r\n* 2020-05-21 1.24.1\r\n    * Fixed a problem with conditions and array.      \r\n* 2020-05-21 1.24\r\n    * Cleanups\r\n* 2020-04-07 1.23.2\r\n    * Solved a problem with datetimestring and a defnatural\r\n* 2020-04-07 1.23.1\r\n    * Solved a problem with validation and input. It failed to validate.\r\n    * Solved a problem where the default value is a string and the type is a datetimestring.\r\n* 2020-02-01 1.23\r\n    *  Solved a problem in endConversion() when the default value is \"\" or null (or not a DateTime object), the type is \r\n    \"datetimestring\", and the value is missing.\r\n    * Practically all methods were tested.\r\n    * resetValidation() now allows to delete all messages.\r\n    * Fixed the validation \"ne\"\r\n* 2020-01-04 1.22\r\n    * New conditions 'mime','minetype','exist','notexist',etc.\r\n    * Condition 'eq' and 'ne' allows a simple or an array of values.\r\n* 2020-01-03 1.21\r\n    * ValidationOne::runConditions() now allows (for file type), conditions architecture and compression\r\n    * ValidationOne::getFileExtension() now could return the extension as mime\r\n    * ValidationOne::getFileMime() new method that returns the mime-type of a file.\r\n* 2019-11-27 1.20\r\n  * Fixed the name countErrorOrWaring-\u003ecountErrorOrWarning\r\n* 2019-11-27 1.19 \r\n  * Added new field MessageContainer.errorOrWarning \r\n  * Added new method MessageLocker.countErrorOrWaring()\r\n* 2019-10.01 1.18 Added compatibility for  phpunit/phpunit 5.7 and 6.5\r\n* 2019-10-01 1.17 Fixed a bug. If the input is zero, then it is considered as null.\r\n* 2019-08-10 1.16 Solved a problem with the datestring/datetimestring.\r\n* 2019-08-07 1.15 \r\n* * Added the type datestring and datetimestring. It reads a string, and it converts into another string (as date or datetime)\r\n* * Code formatted\r\n* 2019-03-08 1.14 Added getFile() to upload a file.\r\n* 2018-12-15 1.13 Added phpunit and travis.\r\n* 2018-10-29 1.12 getFile now it's available via ValidationOne()\r\n* 2018-10-22 1.11 Some fixes. Now isEmpty is called isMissing\r\n* 2018-10-22 1.10 New Features\r\n* * Added ValidationInputOne, now the fetchs are done by  this class (SRP principle)\r\n* * Added a fix with the input, when the value expected is an array, but it's returned a single value\r\n* 2018-10-15 1.9 Added some extra features\r\n* 2018-10-15 1.8 Some fixes and phpdocs, a new example\r\n* 2018-10-15 1.7 Added method addMessage() in ValidationOne. Now ErrorItem/ErrorList is called MessageLocker and MessageContainer\r\n* 2018-10-06 1.5 added method first() in MessageLocker \r\n* 2018-10-03 1.4 added defaultNatural()\r\n* 2018-10-02 1.3 basicvalidation() was deleted. It was restored.\r\n* 2018-10-02 1.2 array() is now isArray()\r\n* 2018-09-30 1.1 Some fixes\r\n* 2018-09-29 1.0 first version\r\n\r\n## todo\r\n* More examples\r\n* Documentation\r\n\r\n\r\n## Note\r\n\r\nIt's distributed as dual license, as LGPL-v3 and commercial.\r\n\r\nYou can use it freely in your close source project. However, if you change this library, then the changes must be disclosed.\r\n\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feftec%2Fvalidationone","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feftec%2Fvalidationone","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feftec%2Fvalidationone/lists"}