PHP code example of inpsyde / validator

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

    

inpsyde / validator example snippets


$value = 8;

$between = new Inpsyde\Validator\Between(['min' => 10, 'max' => 20, 'inclusive' => false]);

if ( $between->is_valid($value) ) {
  echo "Value {$value} is between 10 and 20".
} else {
  echo "Value {$value} is not between 10 and 20".
}

$not_in_array = Negate::with_validator( new InArray( [ 'haystack' => [ 'foo', 'bar' ] ] ) );

$not_in_array->is_valid( 'hello' ); // true
$not_in_array->is_valid( 'foo' ); // false

$array_of_strings = Bulk::with_validator( new Type( [ 'type' => 'string' ] ) );

$array_of_strings->is_valid( [ 'foo', 'bar' ] ); // true
$array_of_strings->is_valid( [ 'foo', true  ); // false

$has_post = Pool::with_validator( new Type( [ 'type' => 'WP_Post' ] ) );

$has_post->is_valid( [ 'foo', new \WP_Post([ 'id' => 1 ]) ] ); // true
$has_post->is_valid( [ 'foo', true  ); // false

use Inpsyde\Validator;

$two_items_string_array = new Validator\Multi(
	['stop_on_failure' => TRUE ],
	[
		new Validator\Type( [ 'type' => 'array' ] ),
		new Validator\Size( [ 'type' => 2 ] ),
		Validator\Bulk::with_validator( new Validator\Type( [ 'type' => 'string' ] ) ),
	]
);

$two_items_string_array->is_valid( [' foo', 'bar' ] ); // true
$two_items_string_array->is_valid( [ 'foo', 1 ] ); // false
$two_items_string_array->is_valid( [ 'foo', 'bar', 'baz' ] ); // false


use Inpsyde\Validator;

$two_items_string_array = Validator\Multi::with_validators(
	new Validator\Type( [ 'type' => 'array' ] ),
    new Validator\Size( [ 'type' => 2 ] ),
    Validator\Bulk::with_validator( new Validator\Type( [ 'type' => 'string' ] ) ),
);

use Inpsyde\Validator;

$two_items_string_array = Validator\Multi::with_validators(...$validators)->stop_on_failure();

use Inpsyde\Validator;

$custom_range = Validator\MultiOr::with_validators(
	new Validator\Between( [ 'min' => 5, 'max' => 10 ] ),
    new Validator\Between( [ 'min' => 50, 'max' => 100 ] ),
);

$custom_range->is_valid( 7 ) // true
$custom_range->is_valid( 30 ) // false
$custom_range->is_valid( 60 ) // true

$configuration = [
	'between'   => [ 'min' => 10, 'max' => 20 ],
	'not-empty' => [],
	'in_array'  => [ 'haystack' => [ 'a', 'b', 'c' ] ]
];

$factory = new Inpsyde\Validator\ValidatorFactory();

$validators = [];

foreach($configuration as $identifier => $options) {

	$validators[] = $factory->create( $identifier, $options);
}

$configuration = [
	'Between'  => [ 'min' => 10, 'max' => 20 ],
	'NotEmpty' => [],
	'InArray'  => [ 'haystack' => [ 'a', 'b', 'c' ] ]
];

use Inpsyde\Validator;

$between = new Validator\Between([ 'min' => 10, 'max' => 20, 'inclusive' => false ]);

if ( ! $between->is_valid() ) {

	$logger = new Validator\Error\WordPressErrorLogger();
	$logger->log_error( $between->get_error_code(), $between->get_input_data() );
	
	foreach( $logger->get_error_messages() as $error ) {
		echo "<p>{$error}</p>";
	}
}

use Inpsyde\Validator\Error;

$logger = new Error\WordPressErrorLogger();
$logger->use_error_template( Error\ErrorLoggerInterface::NOT_BETWEEN, 'Hey, the value %value% is not ok.' );

use Inpsyde\Validator\Error;

$custom_templates = [
	Error\ErrorLoggerInterface::NOT_BETWEEN        => 'Hey, the value %value% is not ok.',
	Error\ErrorLoggerInterface::NOT_BETWEEN_STRICT => 'Hey, the value %value% is not ok. Really.' 
];

$logger = new Error\WordPressErrorLogger( $custom_templates );

use Inpsyde\Validator\Error;

$logger = new Error\WordPressErrorLogger();

$logger->log_error(
	$validator->get_error_code(),   // code
	$validator->get_input_data(),   // input data
	'%value% is wrong, try again.', // custom error message template
);

use Inpsyde\Validator;

$validator = new Validator\DataValidator();

$validator
	->add_validator_with_message( new Validator\NotEmpty(), 'The given value must not be empty.' )
	->add_validator( new Validator\Url([ 'check_dns' => true ]) );
	
$validator->is_valid([
	'http://www.example.com',
	'http://example.com',
	'this-will-fail'
]);

use Inpsyde\Validator;

$validator = new Validator\DataValidator();

$validator
	->add_validator_by_key( new Validator\NotEmpty(), 'name', 'Name cannot be empty.' )
	->add_validator_by_key( new Validator\Url(), 'homepage', 'Homepage must be a valid URL.' )
	
$valid = $validator->is_valid([
	'name'     => 'Inpsyde',
	'homepage' => 'http://www.inpsyde.com',
]);

if (! $valid) {
	foreach( $validator->get_error_messages() as $error ) {
		echo "<p>{$error}</p>";
    }
}

use Inpsyde\Validator\Error;
use Inpsyde\Validator\DataValidator;

$custom_templates = [
	Error\ErrorLoggerInterface::NOT_BETWEEN        => 'Hey, the value %value% is not ok.',
	Error\ErrorLoggerInterface::NOT_BETWEEN_STRICT => 'Hey, the value %value% is not ok. Really.' 
];

$logger = new Error\WordPressErrorLogger( $custom_templates );

$validator = new DataValidator( $logger );

use Inpsyde\Validator;

$validator = new DataValidator();

$validator->add_validator_by_key(
	new Validator\NotEmpty(),
	[ 'key' => 'username', 'label' => __( 'User name', , 'txtdomain' ) ], // key param is an array here
	sprintf( __( '%s must not be empty.', 'txtdomain' ), %key% )
);

if ( ! $validator->is_valid( [ 'username' => '' ] ) ) {
	$messages = $validator->get_error_messages();
}

namespace MyPlugin\Validator;

use Inpsyde\Validator\ExtendedValidatorInterface;
use Inpsyde\Validator\GetErrorMessagesTrait;
use Inpsyde\Validator\ValidatorDataGetterTrait;
use Inpsyde\Validator\Error\ErrorLoggerInterface;

class YesNo implements ExtendedValidatorInterface {

	const ERROR_CODE = 'not_yes_no';

	use GetErrorMessagesTrait;
	use ValidatorDataGetterTrait;
	
	public function is_valid( $value ) {
	
		/** @see ValidatorDataGetterTrait */
		$this->input_data[ 'value' => $value ]; 
		
		if ( ! is_string( $value ) ) {
			// this is a default error
			$this->error_code = ErrorLoggerInterface::INVALID_TYPE_NON_STRING;
			
			return false;
		}
			
		if ( ! in_array( strtolower( $value ), [ 'yes', 'no' ], true ) ) {
		    // custom error
			$this->error_code = self::ERROR_CODE;
			
			return false;
		}
		
		return true;
	}
 
}

namespace MyPlugin;

use Inpsyde\Validator\DataValidator;
use Inpsyde\Validator\Error\WordPressErrorLogger;

$yes_no_message = sprintf(
	__( 'Accepted values are only "yes" and "no". "%s" was given.', 'txtdmn' ),
	'%value%'
);

$logger = new WordPressErrorLogger([ Validator\YesNo::ERROR_CODE => $message ]);

$validator = new DataValidator( $logger );

$validator->add_validator_by_key( new Validator\YesNo(), 'accepted' );