PHP code example of wscore / leanvalidator

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

    

wscore / leanvalidator example snippets


use Wscore\LeanValidator\Validator;

$data = [
    'name' => 'John Doe',
    'age' => 25,
    'email' => '[email protected]'
];

$v = Validator::make($data);

$v->field('name')->int()->between(18, 99);
$v->field('email')->email();

if ($v->isValid()) {
    // Get only the validated data
    $validated = $v->getValidatedData();
} else {
    // Get error messages as a flat array [field_path => with]
    $errors = $v->getErrorsFlat();
}

$v->field('age')
  ->);

$v->defaultMessage = 'Invalid input!';
$v->defaultMessageRequired = 'Cannot skip this field!';

$v->addError('general', 'Something went wrong!');             // Manual level
$v->field('age', 'Please enter your age (must be above 18)') // Field level default
  ->l (applied to next rule)

// Get all errors as a flat array [field_path => first_message]
$errors = $v->getErrorsFlat();

// Example:
// [
//   'email' => 'Please enter a valid email.',
//   'address.city' => 'This field is 

// If field is 'address[city]', it will look up 'address.city'
$error = $bag->firstFromFormName('address[city]');

$v->field('extra_info')->optional()->string();

// With default value
$v->field('status')->optional('active')->string();

$v->field('name')->with
$v->field('title')->

// 'state' is ate')->

// 'state' is ate')->

// 'confirm_password' is ord')->

// 'guest_email' is ail')->

// 'name' is ame')->type'] ?? '') === 'personal';
})->string();

$v->field('type')->

// BackedEnum (string or int)
$v->field('status')->enum(StatusEnum::class);

// UnitEnum
$v->field('type')->enum(TypeEnum::class);

// Using in() with Enum::cases()
$v->field('role')->in(RoleEnum::cases());

$v->field('tags')->asList('string');
// Integer elements between 0 and 100 (each element must be a PHP int)
$v->field('scores')->asList('between', 0, 100);

$v->field('tags')->arrayCount(1, 5, 'Please provide 1 to 5 tags');

$data = ['address' => [
    'post_code' => '123-1234', 
    'town' => 'TOKYO', 
    'city' => 'Meguro',
]];
$v = Validator::make($data);

$v->field('address')->tring();
});
if ($v->isValid()) {
    $validated = $v->getValidatedData();
} // ['address' => ['post_code' => '123-1234', 'town' => 'TOKYO', 'city' => 'Meguro']] }

$data = [
    'users' => [
        ['name' => 'John', 'email' => '[email protected]'],
        ['name' => 'Jane', 'email' => '[email protected]'],
    ]
];

$v = Validator::make($data);
$v->field('users')->asListObject(function(Validator $child) {
    $child->field('name')->

// Using a closure
$v->field('username')->apply(fn($value) => !in_array($value, ['admin', 'root']));

// Using a closure that operates on the validator instance
$v->field('zip')->apply(function() {
    $this->regex('/^\d{3}-\d{4}$/');
});

// Using external functions
$v->field('count')->apply('is_numeric');

// Using first-class callables
$v->field('price')->apply($myValidator->checkPrice(...));

// Using external rule classes (instantiated automatically)
$v->field('token')->apply(MyCustomRule::class, $options);

// Using invokable objects
$v->field('price')->apply(new MyInvokableRule(), $minPrice);

use Wscore\LeanValidator\Validator;
use Wscore\LeanValidator\ValidatorData;
use Wscore\LeanValidator\ValidatorRules;

class MyValidatorRules extends ValidatorRules
{
    public function postCode(): static
    {
        return $this->regex('/^\d{3}-\d{4}$/');
    }

    public function hiragana(): static
    {
        return $this->regex('/^[\x{3040}-\x{309F}\s]+$/u');
    }
}

class MyValidator extends Validator
{
    protected function createRules(): ValidatorRules
    {
        return new MyValidatorRules($this);
    }

    /** @return MyValidatorRules */
    public function field(string $key, ?string $errorMsg = null): ValidatorRules
    {
        return parent::field($key, $errorMsg);
    }
}

// Usage: IDE will suggest postCode() and hiragana()
$v = MyValidator::make($data);
$v->field('zip')->

use Wscore\LeanValidator\Rule\Ja;

$v = Validator::make($data);
$v->field('name_kana')->

use Wscore\LeanValidator\Rule\Net;
use Wscore\LeanValidator\Rule\Date;

$v = Validator::make($data);
$v->field('ip_address')->tart_date')->apply(Date::notFutureDate());

use Wscore\LeanValidator\Rule\Date;

$v = Validator::make($data);
$v->field('birthday')->pply(Date::htmlTime());
$v->field('billing_month')->apply(Date::htmlMonth());
$v->field('reporting_week')->apply(Date::htmlWeek());

// Disallow future dates (including today is allowed)
$v->field('birthday')->apply(Date::notFutureDate());

class ValidatorRulesJa extends ValidatorRules
{
    public function hiragana(): static { return $this->apply(Ja::hiragana()); }
    public function zip(): static { return $this->apply(Ja::zip()); }
}

$s->toDigits('user.tel');           // Target 'tel' inside 'user'
$s->toDigits('items.*.code');       // Target 'code' in all elements of 'items'
$s->skipTrim('user.*');             // Skip trim for all direct children of 'user'

$s = new Sanitizer();
$s->addRule('stars', function($value) {
    return str_repeat('*', strlen($value));
});

$s->apply('stars', 'password');

use Wscore\LeanValidator\Sanitizer;

$data = [
    'name' => '  John Doe  ',
    'tel' => '03-1234-5678',
    'password' => '  secret  ',
    'items' => [
        ['code' => ' A-123 '],
        ['code' => ' B-456 '],
    ]
];

$s = new Sanitizer();

// Configure sanitization
$s->skip('password')           // Do not trim or clean password
    ->toDigits('tel')             // Remove non-digit characters
    ->toDigits('items.*.code');   // Use dot-notation and wildcards for nested data
// Apply sanitization
$cleanData = $s->clean($data);
// $cleanData['name'] => 'John Doe'
// $cleanData['tel'] => '0312345678'
// $cleanData['password'] => '  secret  '
// $cleanData['items'][0]['code'] => '123'