PHP code example of sujal / validation

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

    

sujal / validation example snippets




ujal\Validation\Field;
use Sujal\Validation\Schema;
use Sujal\Validation\Validator;
use Sujal\Validation\Rules\Required;
use Sujal\Validation\Rules\Email;

$schema = Schema::make(
    Field::named('email')->rules(new Required(), new Email()),
);

$result = Validator::check([
    'email' => '[email protected]',
], $schema);

if ($result->passed()) {
    print_r($result->validated());
} else {
    print_r($result->errors()->all());
}



use Sujal\Validation\Field;
use Sujal\Validation\Schema;
use Sujal\Validation\Validator;
use Sujal\Validation\Rules\Required;
use Sujal\Validation\Rules\Email;
use Sujal\Validation\Rules\Min;
use Sujal\Validation\Rules\Confirmed;
use Sujal\Validation\Rules\In;

// This is the data you want to check — form POST, JSON body, etc.
$input = [
    'name' => 'Ada Lovelace',
    'email' => '[email protected]',
    'password' => 'secret123',
    'password_confirmation' => 'secret123',
    'role' => 'admin',
];

$schema = Schema::make(
    Field::named('name')->rules(new Required(), new Min(2)),
    Field::named('email')->rules(new Required(), new Email())->label('email address'),
    Field::named('password')->rules(new Required(), new Min(8), new Confirmed())->bail(),
    Field::named('role')->rules(new Required(), new In('admin', 'editor', 'viewer')),
);

$result = Validator::check($input, $schema);

if ($result->failed()) {
    foreach ($result->errors()->all() as $field => $messages) {
        foreach ($messages as $message) {
            echo $field . ': ' . $message . PHP_EOL;
        }
    }
}

$input = [
    'email' => '[email protected]',
    'password' => 'secret123',
    'name' => 'Ada',
];

$credentials = Schema::make(
    Field::named('email')->rules(new Required(), new Email()),
    Field::named('password')->rules(new Required(), new Min(8)),
);

$profile = Schema::make(
    Field::named('name')->rules(new Required(), new Min(2)),
);

$registration = $credentials->merge($profile);

$result = Validator::check($input, $registration);

Field::named('user.profile.email')->rules(new Required(), new Email())

$schema = Schema::make(
    Field::named('items.*.email')->rules(new Required(), new Email()),
);

$result = Validator::check([
    'items' => [
        ['email' => '[email protected]'],
        ['email' => 'bad'],
    ],
], $schema);

// Fails on items.1.email

use Sujal\Validation\Rules\Nullable;
use Sujal\Validation\Rules\Sometimes;

// null is allowed; other rules skipped when value is null
Field::named('nickname')->rules(new Nullable(), new Email())

// only validate when the key exists (PATCH-friendly)
Field::named('email')->rules(new Sometimes(), new Email())

$schema = Schema::make(
    Field::named('email')
        ->rules(new Required(), new Email())
        ->label('work email')
        ->message('Required', 'Please enter your work email.'),
)->messages([
    // schema-wide catalog: attribute.RuleKey
    'email.Email' => 'That work email does not look right.',
]);

$result->failed();
$result->errors()->all();
$result->errors()->first('email');
$result->errors()->firstMessage();
$result->errors()->flatten();
$result->validated(); // nested array of fields that passed

use Sujal\Validation\ValidationException;

$input = [
    'email' => '[email protected]',
];

$schema = Schema::make(
    Field::named('email')->rules(new Required(), new Email()),
);

try {
    $result = Validator::checkOrFail($input, $schema);
    $clean = $result->validated();
} catch (ValidationException $e) {
    $messages = $e->errorMessages();
}

Field::named('email')->rules(new Email()) // '' passes

use Sujal\Validation\Rules\RequiredIf;

Field::named('company_name')->rules(
    new RequiredIf('account_type', 'business')
)

use Sujal\Validation\Rules\Callback;

Field::named('sku')->rules(
    new Required(),
    new Callback(
        fn (string $attribute, mixed $value): bool => is_string($value)
            && str_starts_with($value, 'SKU-'),
        'The :attribute must start with SKU-.'
    )
)



namespace App\Rules;

use Sujal\Validation\Contracts\Rule;

final class StartsWithSku implements Rule
{
    public function passes(string $attribute, mixed $value, array $data = []): bool
    {
        return is_string($value) && str_starts_with($value, 'SKU-');
    }

    public function message(): string
    {
        return 'The :attribute must start with SKU-.';
    }

    public function replacements(): array
    {
        return [];
    }
}

use Sujal\Validation\ValidationEngine;
use Sujal\Validation\Validator;

$input = [
    'email' => '[email protected]',
];

$schema = Schema::make(
    Field::named('email')->rules(new Required(), new Email()),
);

$engine = new ValidationEngine(
    reader: $yourDataReader,
    formatter: $yourFormatter,
);

$validator = new Validator(engine: $engine);
$result = $validator->validate($input, $schema);