It's a PHP library for fetches and validate fields and store messages in different containers(including error, warning, info , and success) depending on the conditions.
The ideology behind this library is simple: 3 classes, a simple dependencies and runs in PHP 7.1 and higher, so it could run in practically any PHP project, including WordPress, Laravel, core PHP project, etc.
Examples
Tutorial Form and Table with PHP
It is an example of functionality. A typical example is more complex, even if it's only a few lines of code.
Let's say we want to validate a value an input value (get) called "id", we could do the next things:
use eftecValidationOne;
$val=new ValidationOne();
$r = $val->def('ERROR')
->type('integer')
->ifMissingThenDefault()
->condition("eq", "It's not equals to 10", 10)
->condition("eq", "It's not equals to 30 (info)", 30, 'info')
->ifFailThenDefault()
->get('id'); // <-- end of the chain
But where is the error?. The messages are stored in messageList
var_dump($val->messageList->allArray()); // here we show all messages of any kind of type.
var_dump($val->messageList->errorCount); // returns the number of errors.
var_dump($val->errorcount()); // returns the number of errors (alternative)
var_dump($val->hasError()); // returns true if there is an error.
However, we could also show a message by type (error, warning..) and only message by a specific identifier.
var_dump($val->messageList->get('id')->allErrorOrWarning()); // All error or warning contained in the key "id".
Why the messages are store in some structure?. Is it not easy to simply return the error?
An 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.
The start of the chain usually it is written at the end of the code.
The methods allowed are:
Example:
$val=new ValidationOne();
$id = $val->type('integer')->get('id');
$id = $val->type('integer')->post('id');
$id = $val->type('integer')->request('id');
$id = $val->type('integer')->set('123','id');
$val=new ValidationOne();
$id = $val->type('integer')->get('id'); // $_GET['id']
$val=new ValidationOne('frm'); // we set a prefix for every reading.
$id = $val->type('integer')->get('id'); // $_GET['frm_id']
condition ($condition, $message = "", $conditionValue = null, $level = 'error', $key = null)
It adds a condition that it depends on the type of the input.
@param string $condition
number:req,eq,ne,gt,lt,gte,lte,between,null,notnull
string:req,eq,ne,minlen,maxlen,betweenlen,null,notnull,contain,notcontain
,alpha,alphanum,text,regexp,email,url,domain
date:req,eq,ne,gt,lt,gte,lte,between
datestring:req,eq,ne,gt,lt,gte,lte,between
boolean:req,eq,ne,true,false
file:minsize,maxsize,req,image,doc,compression,architecture,ext
function:
fn.static.Class.methodstatic
fn.global.function
fn.object.Class.method where object is a global $object
fn.class.Class.method
fn.class.namespaceClass.method
@param string $message
Message could use the next variables '%field','%realfield','%value','%comp','%first','%second'
Field | Description | Example |
---|---|---|
%field | name of the field, it could be the friendid or the actual name | CustomerID |
%realfield | name of the field (not the friendid) | Customer Identifier |
%value | current value of the field | John |
%comp | value to compare (if any) | |
%first | first value to compare (if the compare value is an array) | |
%second | second value to compare (if the compare value is an array) | |
%key | key used (for input array) |
@param null $conditionValue
@param string $level (error,warning,info,success). The level of the error. See MessageContainer for further information
@param string $key If the key is not null then it is used to add more than one condition by key
@return ValidationOne
Note: if the value is null and isNullValid() is true, then the conditions are ignored. If the value is missing and isMissingValid() is true, then the conditions are ignored. If the value is empty ('') and isEmptyValid() is true, then the conditions are ignored. If the value is empty ('') or null and isNullOrEmptyValid() is true, then the conditions are ignored. isNullValid(),isMissingValid(),isNullOrEmptyValid() and isEmptyValid() are useful when we want to validate a value only if it exists or if the value is set.
Example:
$validation->def(null)
->type('integer')
->condition('eq','%field %value is not equal to %comp ',50)
->condition('eq','%field %value is not equal to %comp ',60)
->set('aaa','variable2');
type | description |
---|---|
integer | (numeric) it allows a number without decimal |
unixtime | (numeric) it allows a number without decimal |
boolean | (boolean) it stores true or false. The input could vary (empty, zero or null = false, otherwise true) |
decimal | (numeric) it allows a number with decimal |
float | (numeric) it allows a number with decimal |
varchar | (string) it allows any input |
string | (string) it allows any input |
date | (date) the input could be a DateTime or a string. The value is stored as an object DateTime |
datetime | (date) the input could be a DateTime or a string. The value is stored as an object DateTime |
datestring | (date) the input could be a DateTime or a string. The value is stored as a string |
datetimestring | (date) the input could be a DateTime or a string. The value is stored as a string |
file | (file) the input is a string, and it's store as a string, but it adds special validation |
Input type | Condition | |
---|---|---|
number | gt,lt,gte,lte,between | |
string | minlen,maxlen,betweenlen,contain ,notcontain,alpha,alphanum,text,regexp,email,url,domain |
|
date | gt,lt,gte,lte,between | |
datestring | gt,lt,gte,lte,between | |
boolean | true,false | |
file | minsize,maxsize,req,image,doc,compression,architecture,ext | |
* (it applies for any type) | req,eq,ne,null,notnull,empty,notempty | |
* | function | |
* | fn.static.Class.methodstatic | |
* | fn.global.function | |
* | fn.object.Class.method where object is a global $object | |
* | fn.class.Class.method | |
* | fn.class.namespaceClass.method |
Condition | Description | Value Example |
---|---|---|
architecture | The extension of the file must be an architecture file (dwg, etc.) | |
between | The number must be between two values | [0,20] |
betweenlen | The length of the text must be between two values | [0,20] |
compression | The extension of the file must be an compression file | |
contain | The text must contain a value | "text" |
doc | The extension of the file must be a document file | |
eq (it could be an array or value) / == | The value must be equals to The value must be contained in a array |
"text",["text","text2"] |
exist | The file or value must exist (it could be null/empty) | |
missing / notexist | The file or value must not exists or be null/empty | |
required (or req) | The value must not be null or empty | |
ext | The extension (file) must be in the list of extensions | ["ext1","ext2","ext3"] |
false | The value must be false (===false) | |
fn.class.namespaceClass.method | The method of a class must returns true | |
fn.class.Class.method | The method of a class must returns true | |
fn.global.function | The global function must returns true | |
fn.object.Class.method where object is a global $object | The method of a global object must returns true | |
fn.static.Class.methodstatic | The static method of a class must returns true | |
function | The function must returns true | |
gt / > | The value must be greater than | 123 |
gte / >= | The value must be greater or equal than | 123 |
image | The extension of the file must be an image file | |
lt / < | The value must be less than | 123 |
lte / <= | The value must be less or equal than | 123 |
maxlen | The maximum length of a string | 123 |
maxsize | The maximum size of a file | 123 |
minlen | The minimum length of a string | 123 |
minsize | The minimum size of a file | 123 |
mime (the value to compare could be an string or array) | The mime type of a file | "application/msword" or ["application/msword","image/gif"] |
mimetype | The mime type (without subtype) of a file | "application" or ["application,"image"] |
ne / != (the value to compare could be an single value or array) | The value must not be equals. Or the value must not be contained in a array |
123,[123,345],["aa","bb"] |
notcontain | The value must not contain a value | "text" |
notnull | The value must not be null | |
null | The value must be null | |
empty | The value must be empty (i.e. "",0,null) | |
notempty | The value must not be empty (i.e. not equals to "",0,null) | |
req | The value must exists | |
true | The value must be true (===true) |
Examples:
$validation->def(null)
->type('integer')
->condition('eq','%field %value is not equal to %comp ',50)
->condition('between','%field %value must be between 1 and 50 ',[1,50])
->condition('eq','%field %value is not equal to %comp ',60)
->condition('eq','%field %value is not equal to %comp ',[60,200]) // eq allows a single or array
->condition('fn.static.Example.customval','the function does not work')
->condition('req')
->condition('lt',"es muy grande",2000,'warning')
->condition('eq','%field %value is not equal to %comp',50)
->condition('fn.static.Example.fnstatic','the static function does not work')
->condition('fn.static.somespaceSomeclass.methodStatic',null)
->condition('fn.global.customval','The global function does not work')
->condition('fn.object.example.fnnostatic','the function object does not work')
->condition('fn.class.somespaceSomeclass.method','The function some class does not work')
->condition('fn.class.Example.fnnostatic','la funcion class no funciona');
// ->condition('fn.static.Example.customval','la funcion no funciona')
function customval($value,$compareValue) {
return true;
}
Sometimes we need to use a custom condition. We could create a global variable, a static function, or even a method
inside a class.
Every method or function created must have two parameters (with any name):
For example, what if we need to evaluate if some id does not exist in the Database?
$validation->condition('fn.global.idExist','The id already exist!')->get("id");
function idExist($id,$compare=null) {
// select count(*) c from table where id=$id
if($c>0) {
return true;
} else {
return false;
}
}
Note: if we need to specify a namespace, then we could use the notation: namespaceSomeClass
$validation->condition('fn.global.customfn'); // global
$validation->condition('fn.static.SomeClass.staticfn'); // calling a static method inside the class SomeClass.
$validation->condition('fn.class.SomeClass.noStaticFn'); // method inside a class,it creates an instance of an object then it calls the method
$validation->condition('fn.object.myObject.noStaticFn'); // method inside a class, it uses an instance called $myObject
// global function
function customfn($value,$compareValue) {
// returns true or false
}
// static function
$myObject=new SomeClass();
class SomeClass {
public static function staticfn($value,$compareValue) {
// returns true or false
}
public function noStaticFn($value,$compareValue) {
// returns true or false
}
}
When we validate an object, it could store the information inside the Message Container (also called Message List).
MessageContainer (EFTEC/MessageContainer) contains a list messages in a hierarchy way:
Container (usually only 1 for all the project)
Lockers (from zero to many)
Messages (from zero to many and grouped by level)
$container->get('locker20')->firstError(); // it returns the first message of error in the locker20 that is part of the container.
Messages are leveled as follows
id | Description | Example |
---|---|---|
error | The message is an error, and it must be solved. It is our show stopper. | Database is down |
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 |
info | The message is information. For example, to log or debug an operation. | Log is stored |
success | The message is a successful operation | Order Accepted |
Function | Description | Example |
---|---|---|
addMessage($idLocker, $message, $level = 'error') | It adds a message inside a locker. Usually, it is done automatically by the library but you can add messages manually via code. |
$this->addMessage('pwd','the password is required','error'); |
getMessage($withWarning = false) | It gets the first error message or empty if none | $this->getMessage(); |
getMessages($withWarning = false) | It gets all the error messages or empty if none | $this->getMessages(); |
getMessageId($idLocker) | It gets a MessageLocker object (see EFTEC/MessageContainer for more information) | $obj=$this->getMessageId('pwd'); |
errorCount(includeWarning=false) | It gets the error count | $count=$this->errorCount(); |
hasError($includeWarning=false) | It returns true if there is an error | $fail=$this->hasError(); |
Field | Description | Example |
---|---|---|
$messageList | It gets all the container. It returns an object of the type MessageContainer | $container=$this->messageList; |
You can see more information about MessageContainer in EFTEC/MessageContainer
Example:
$validation->addMessage('idlocker','this field is required','error'); // it adds a message inside a locker.
$validation->messageList->get('idlocker')->allError(); // it gets all errors from the locker idlocker
$validation->getMessages(true); // it gets all messages of error or warning from all the lockers.
We also could work with dates. There are several types of date formats.
type | description |
---|---|
date | (date) the input could be a DateTime or a string. The value is stored as an object DateTime |
datetime | (date) the input could be a DateTime or a string. The value is stored as an object DateTime |
datestring | (date) the input could be a DateTime or a string. The value is stored as a string using the field $dateOutputString |
datetimestring | (date) the input could be a DateTime or a string. The value is stored as a string using the field $dateLongOutputString |
There 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.
Name Field | Description | Default value |
---|---|---|
$dateShort | It is the (expected) input format for date (short) | d/m/Y |
$dateLong | It is the (expected) input format (with date and time) | d/m/Y H:i:s |
$dateOutputString | It is the output format (for datestring) | Y-m-d |
$dateLongOutputString | It is the output format (for datetimestring) | Y-m-dTH:i:sZ |
$r=getVal()->type('datestring')->set('31-12-2019'); // 2019-12-31 note: the default input value is d/m/Y, not m/d/Y
We can change the date format by changing the fields or calling the next functions
Setting the format of the dates (input short, input long, output short and output long)
$validation->setDateFormat('m/d/Y', 'm/d/Y H:i:s', 'Y-m-d', 'Y-m-dTH:i:sZ')
We set the format of the dates to the default configuration
$validation->setDateFormatDefault();
We set the format to the dates to :
Name | Format |
---|---|
input short | m/d/Y |
input long | m/d/Y H:i:s |
output short | Y-m-d |
output long | Y-m-dTH:i:sZ |
$validation->setDateFormatEnglish()
By default, this library does not generate exceptions. However, it is possible to generate exceptions if the message is of the type ERROR and/or WARNING.
With this method, if the container generates an error, then it is stored also generates a new exception.
Note: By default, most messages are of the type ERROR.
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.
try {
$validation->type('integer')
->throwOnError() // for errors only
->set('hello', 'field1');
// or you could use:
$validation->type('integer')
->throwOnError(true,true) // for errors and warnings
->set('hello', 'field1');
$this->fail('this value means the throw failed');
} catch(Exception $ex) {
$this->assertEquals('field1 is not numeric',$ex->getMessage());
}
There are four different ways to deal with empty values in this library.
$validation->exist()->set(null); // is valid.
$validation->exist()->set(''); // is valid.
$validation->exist()->get('field'); // is valid only if $_GET['field'] exist (even if it is null)
$validation->required()->set(null); // is not valid.
$validation->required()->set(""); // is not valid.
$validation->required()->set('hi'); // is valid.
$validation->notnull()->set(null); // is not valid.
$validation->notnull()->set(""); // is valid.
$validation->notnull()->set('hi'); // is valid.
$validation->notempty()->set(null); // is valid.
$validation->notempty()->set(""); // is not valid.
$validation->notempty()->set('hi'); // is valid.
Also, there are 4 ways to accept missing values, null or empty, bypassing any condition.
$validation->isNullValid()->condition(....)->set(null); // is valid no matter the condition.
$validation->isNullorEmptyValid()->condition(....)->set(null); // is valid no matter the condition.
$validation->isEmptyValid()->condition(....)->set(''); // is valid no matter the condition.
$validation->isMissingValid()->condition(....)->get('field'); // If the field is missing, then is valid no matter the condition
It is used when we need to validate when an input has some value unless the value is missing, empty or null.
isNullorEmptyValid() is equals than to call: isEmptyValid()->isNullValid()
Also, those operators could be stacked.
$validation
->isNullorEmptyValid()
->isMissingValid()
->condition(....)
->set(....); // this expression is valid if the value is null, empty(''), the value is missing, no matter the conditions.
We could set a default value. This value could be as fallback when there is an error. The default value is never converted or processed.
$validation
->def(-1)
->type('integer')
->ifFailThenDefault()
->set(...); // if the operation fails, then it returns -1
Trim 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.
$validation->trim()->set(....); // trim both sided
$validation->trim('trim','.,')->set(....); // trim . and ,
$validation->trim('ltrim')->set(....); // trim left sided
$validation->trim('rtrim')->set(....); // trim right sided
Sometimes, 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.