Validator

In older PHP Jet versions, the validator subsystem was a built-in part of the form subsystem. As the name suggests, it is used to validate values, but unlike the previous implementation within forms, it is now fully usable independently. However, in terms of architecture and usage logic, the validator subsystem is very similar to forms. Technically speaking, validation was completely removed from the form subsystem and transformed into this standalone usable subsystem.

Basic overview of validator features and capabilities

  • An open, extensible, and modifiable modular subsystem (like everything in PHP Jet :-) )
  • A large set of ready-made validators.
  • Ability to overload ready-made validators using factories.
  • Ability to create any custom validators.
  • Ability to map validators to any entity (class) using definitions, just like ORM or the form subsystem.

Brief usage example

Basic general usage

$tested_value '#FFC6C6';

$validator Factory_Validator::getValidatorInstanceValidator::TYPE_COLOR );
$validator->setIsRequiredtrue );
if(
$validator->validate$tested_value )) {
    echo 
'Value is valid';
} else {
    echo 
'Value is NOT valid';
    
    echo 
$validator->getLastErrorMessage();
}

Mapping a validator directly to an entity - class

namespace JetApplication;

use 
Jet\BaseObject;
use 
Jet\Entity_Validator_Definition;
use 
Jet\Entity_Validator_Interface;
use 
Jet\Entity_Validator_Trait;
use 
Jet\Validator;
use 
Jet\Validator_Int;


class 
ExapleEntity extends BaseObject implements Entity_Validator_Interface
{
    
    use 
Entity_Validator_Trait;

    #[
Entity_Validator_Definition(
        
typeValidator::TYPE_INT,
        
min_value10,
        
max_value999,
        
error_messages: [
            
Validator_Int::ERROR_CODE_OUT_OF_RANGE => 'Number is out of range (0-999)'
        
]
    )]
    protected 
int $int_property 0;
    
    public function 
getIntProperty(): int
    
{
        return 
$this->int_property;
    }
    
    public function 
setIntPropertyint $int_property ): void
    
{
        
$this->int_property $int_property;
    }
    
}

$object = new ExapleEntity();
$object->setIntProperty10000 );

$validator $object->createValidator();
if(
$validator->validate()) {
    echo 
"OK - object is valid";
} else {
    echo 
"Object is not valid<br><br>";
    
    foreach( 
$validator->getErrors() as $property_path=>$validation_errors ) {
        foreach( 
$validation_errors as $validation_error ) {
            echo 
$property_path.': '.$validation_error->getMessage().'<br>';
        }
    }
}
Previous chapter
InputCatcher
Next chapter
Forms