PHP code example of eftec / validationone

1. Go to this page and download the library: Download eftec/validationone library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

eftec / validationone example snippets


use eftec\ValidationOne;
$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


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.

var_dump($val->messageList->get('id')->allErrorOrWarning()); // All error or warning contained in the key "id".

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

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

$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.\somespace\Someclass.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.\somespace\Someclass.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;
}

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


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


⭐ 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.    
    

$validation->addMessage('idlocker','this field is r(); // it gets all errors from the locker idlocker
$validation->getMessages(true); // it gets all messages of error or warning from all the lockers.


$r=getVal()->type('datestring')->set('31-12-2019'); // 2019-12-31 note: the default input value is d/m/Y, not m/d/Y

$validation->setDateFormat('m/d/Y', 'm/d/Y H:i:s', 'Y-m-d', 'Y-m-d\TH:i:s\Z')

$validation->setDateFormatDefault();

$validation->setDateFormatEnglish()

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

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

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

   $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

$validation
    ->isNullorEmptyValid()
    ->isMissingValid()
    ->condition(....)
    ->set(....); // this expression is valid if the value is null, empty(''), the value is missing, no matter the conditions.

$validation
    ->def(-1)
    ->type('integer')
    ->ifFailThenDefault() 
    ->set(...); // if the operation fails, then it returns -1

$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


$validation->alwaysTrim(); // always trim the next characters " \t\n\r\0\x0B"
$validation->alwaysTrim(true,",."); // always trim , and .
// ...
$validation->alwaysTrim(false);  // we disable the always trim.

$array=$validation->isArray()->request('id');

$array=$validation->isArray(true)->request('id');

$values=getVal()->isArray(true)->request('field'); // ['col1'=>['cocacola','fanta'],'col2'=>[123,123]]
ValidationOne::invertArray($values); // // [['col1'=>'cocacola','col2'=>123],['col1'=>'fanta','col2'=>123]]

$arr=['col1'=>['cocacola','fanta'],'col2'=>[1,2]];
ValidationOne::invertArray($arr); // [['col1'=>'cocacola','col2'=>1],['col1'=>'fanta','col2'=>2]]
'''





### convert()

It 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.

If the value is missing, or it is used the default value, then it is not converted.

| Type              |     | Description                                                                                 | Example                                                                                                                                                                           |
|-------------------|-----|---------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| upper             |     | Converts the value in uppercase                                                             | $this->conversion('upper')->set('Hello World'); // HELLO WORLD                                                                                                                    |
| lower             |     | Converts the value in lowercase                                                             | $this->conversion('lower')->set('Hello World'); // hello world                                                                                                                    |
| ucfirst           |     | Converts the first character in uppercase                                                   | $this->conversion('ucfirst')->set('hello world'); // Hello world                                                                                                                  |
| ucwords           |     | Converts the first character in a word in uppercase                                         | $this->conversion('ucwords')->set('hello world'); // Hello World                                                                                                                  |
| replace           |     | Replace a string by other                                                                   | $this->conversion('replace','hello','world')->set('hello hello'); // world world                                                                                                  |
| sanitizer         |     | Sanitizer the result. It uses filter_var()                                                  | $this->conversion('sanitizer',FILTER_SANITIZE_EMAIL)->set('//[email protected]'); // [email protected]<br />$this->conversion('sanitizer',FILTER_SANITIZE_SPECIAL_CHARS,FILTER_FLAG_STRIP_HIGH) |
| alphanumeric      |     | Sanitize the result by keeping the alphanumeric characters plus underscore :                | this->conversion('alphanumeric')->set('HELLO world_-123'); // HELLOworld_123                                                                                                      |
| alphanumericminus |     | Sanitize the result by keeping the alphanumeric characters plus underscore and minus symbol | this->conversion('alphanumericminus')->set('HELLO world_-123'); // HELLOworld_-123                                                                                                |
| regexp            |     | It calls preg_replace to replace a text                                                     | this->conversion('regexp','/[/^0-9]/','')->set('hello123'); // 123                                                                                                                |
| rtrim             |     | Trim the right characters                                                                   | $this->conversion('rtrim')                                                                                                                                                        |
| ltrim             |     | Trim the left characters                                                                    | $this->conversion('ltrim')                                                                                                                                                        |
| trim              |     | Trim the right and left. It is equivalent to $this->trim()                                  | $this->conversion('trim')->set(' hello '); // hello<br />$this->conversion('trim'," \t\n\r\0\x0B")                                                                                |
| htmlencode        |     | Encode to html content. It uses htmlentities()                                              | $this->conversion('htmlencode')->set('\<b>dog\</b>'); //\&lt;b\&gt;dog\&lt;                                                                                                       |
| htmldecode        |     | Decode from a html. It uses html_entity_decode()                                            | $this->conversion('htmldecode')->set('\&lt;b\&gt;dog\&lt;'); // \<b>dog\</b>                                                                                                      |