PHP code example of phputil / validator

1. Go to this page and download the library: Download phputil/validator 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/ */

    

phputil / validator example snippets


// Suppose that your application receives an object in a JSON like this:
$json = <<<EXAMPLE
{
	"name": "Bob Developer",
	"likes": 150,
	"phone": { "number": "99988-7766", "notes": "WhatsApp, Telegram" },
	"friends": [ "Suzan", "Mike", "Jane" ]
}
EXAMPLE;
// So you transform the JSON into an object
$obj = json_decode( $json );
// Now you want to validate this object, and you create a Validator
$validator = new Validator();
// And define the rules
$rules = array(
	// name must have from 2 to 60 characters
	'name' => array( Rule::LENGTH_RANGE => array( 2, 60 ), Option::LABEL => 'Name' ),
	// likes must be greater or equal to zero
	'likes' => array( Rule::MIN_VAUE => 0 ),
	// for the phone...
	'phone' => array( Rule::WITH => array(
		// number must follow a regex
		'number' => array(
			Rule::REGEX => '/^[0-9]{5}\\-[0-9]{4}$/',
			Option::LABEL => 'Phone Number'
			)
	) ),
	// have a friend limit
	'friends' => array( Rule::MAX_COUNT => 100 )
);
// And define the messages (we also could load it from a JSON file)
$messages = array(
	'en' => array( // "en" means "english" locale. This is the default locale.
		Rule::LENGTH_RANGE => '{label} must have from {min_length} to {max_length} characters.',
		Rule::MIN_VAUE => '{label} must be greater than or equal to {min_value}.',
		Rule::REGEX => '{label} has an invalid format.',
		Rule::MAX_COUNT => '{label} must have up to {max_count} item(s).',
	)
);
$validator->setMessages( $messages );

// Now we will check the object using our rules
$problems = $validator->checkObject( $obj, $rules );
// In this moment, problems will be an empty array because all values passed.
// That is: $problems === array()

// However, lets make our rules harder, just to understand how the validation works
$rules[ 'name' ][ Rule::LENGTH_RANGE ] = array( 2, 5 ); // Max of 5
$rule[ 'friends' ][ Rule::MAX_COUNT ] = 1; // just one friend (the best one :-)

// And check again
$problems = $validator->checkObject( $obj, $rules );
// Now $problems is an array like this:
// array(
//	'name' => array( 'length_range' => 'Name must have from 2 to 5 characters.' ),
//	'friends' => array( 'max_count' => 'friends must have up to 1 item(s)' )
// )
// Which means that we have two fields with problems. The format is:
//  field => hurt rule => message
// For example, the field "name" hurt the "length_range" rule and its message is
// "Name must have from 2 to 5 characters.".
//
// If we need to know whether "name" has a problem, we just check with isset:
if ( isset( $problems[ 'name' ] ) ) {
	echo 'Name has a problem', PHP_EOL;
}
// If we are only interested in the messages, and don't care about the fields,
// we just use the ProblemsTransformer
$messages = ( new ProblemsTransformer() )->justTheMessages( $problems );
var_dump( $messages );
// Will print something like:
// array( 'Name must have from 2 to 5 characters.', 'friends must have up to 1 item(s)' )
//
// That's it for now. Enjoy it!

// Adding a custom rule called "myRule" in which the value should be zero:
$validator->setRule( 'myRule', function( $value ) { return 0 == $value; } );

$value = rand( 0, 5 ); // Value to be checked, a random between 0 and 5 (inclusive)
$rules = array( 'myRule' => true ); // Rules to be checked. In this example, just "myRule".
$problems = $validator->check( $value, $rules ); // check() will return the hurt rules
echo isset( $problems[ 'myRule' ] ) ? 'myRule as hurt' : 'passed';

// Adding a format "myFormat" in which the value should start with "https://"
$validator->setFormat( 'myFormat', function( $value ) {
	return mb_strpos( $value, 'https://' ) === 0;
	} );

$value = 'http://non-https-site.com';
$rules = array( Rule::FORMAT => 'myFormat' ); // rules to be checked
$problems = $validator->check( $value, $rules ); // check() returns the hurt rules
echo isset( $problems[ Rule::FORMAT ] ) ? 'myFormat as hurt' : 'passed';