Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Validation Laravel Package

respect/validation

Powerful PHP validation engine with 150+ tested validators. Build readable, chainable rules like numeric()->positive()->between(). Includes advanced exception handling and thorough docs. Great for complex input validation in any PHP app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require respect/validation
    

    Add to composer.json if using Laravel's autoloader:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Respect\\Validation\\": "vendor/respect/validation/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Validate a user input in a Laravel controller:

    use Respect\Validation\Validator as v;
    
    public function store(Request $request) {
        $validator = v::stringType()->notEmpty()->validate($request->input('name'));
        if ($validator->isValid()) {
            // Proceed with logic
        } else {
            return response()->json(['error' => $validator->getFullMessage()], 422);
        }
    }
    
  3. Key Entry Point: The Validator facade (v::) is the primary interface. Start with the official documentation for validator lists and patterns.


Implementation Patterns

1. Chaining Validators

Leverage fluent interfaces for complex rules:

v::numericVal()
    ->positive()
    ->between(1, 100)
    ->validate($input);

2. Nested Validation

Validate arrays/objects with dot notation:

v::key('user.address.zip', v::numericVal()->length(5))
    ->validate($data);

3. Dynamic Factories

Create validators based on runtime input:

v::factory(function ($input) {
    return v::key('confirm_password', v::equals($input['password']));
})
->assert($request->all());

4. Attribute Validation (PHP 8.0+)

Annotate DTOs for automatic validation:

use Respect\Validation\Validators as v;

class UserDto {
    #[v\Email] public string $email;
    #[v\Between(18, 120)] public int $age;
}

// Validate all annotated properties
v::attributes()->assert($userDto);

5. Short-Circuiting

Stop validation at first failure (optimization for dependent checks):

v::shortCircuit(
    v::key('country', v::countryCode()),
    v::factory(fn($input) => v::key('state', v::subdivisionCode($input['country'])))
)->assert($data);

6. Result-Based Workflows

Inspect validation failures granularly:

$result = v::email()->validate($input);
if ($result->hasFailed()) {
    foreach ($result->getMessages() as $message) {
        // Handle each error (e.g., log, translate)
    }
}

7. Integration with Laravel

  • Form Requests:
    use Respect\Validation\Validator as v;
    
    public function rules() {
        return [
            'email' => v::email()->setMessage('Invalid email format'),
            'age'   => v::between(18, 120),
        ];
    }
    
  • Service Layer:
    public function validateUser(UserRequest $request) {
        $validator = v::allOf(
            v::key('email', v::email()),
            v::key('password', v::length(8, 32))
        );
        $validator->assert($request->validated());
    }
    

8. Custom Validators

Extend for domain-specific rules:

use Respect\Validation\Validator as v;
use Respect\Validation\Rules\Validator;

class StrongPasswordValidator extends Validator {
    public function validate($input) {
        return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/', $input);
    }
}

// Usage
v::newValidator()->setValidator(new StrongPasswordValidator())
    ->validate($password);

Gotchas and Tips

Pitfalls

  1. PHP 8.5 Requirement: Respect/Validation 3.x requires PHP 8.5+. Use 2.x for older PHP versions.

    composer require respect/validation:^2.4
    
  2. validate() vs isValid():

    • validate() returns a ResultQuery (for inspection).
    • isValid() returns a boolean (legacy alias).
    // Prefer:
    $result = v::email()->validate($input);
    if ($result->hasFailed()) { ... }
    
    // Avoid (deprecated):
    if (!v::email()->isValid($input)) { ... }
    
  3. Strict Defaults:

    • Contains, In, StartsWith are strict by default (use notStrict() for loose checks).
    • Each rejects non-iterables (use IterableVal for arrays/objects).
  4. Nested Paths: Deeply nested keys (e.g., user.address.city) may fail if intermediate keys are missing. Use KeyOptional or KeyExists:

    v::keyOptional('user.address.city', v::stringType());
    
  5. Custom Messages:

    • Use templated() for dynamic messages:
      v::numericVal()->templated('{{subject}} must be a number between {{min}} and {{max}}')
          ->between(1, 100);
      
    • Placeholders like {{subject}} (not {{name}} as in v2).
  6. Attribute Validation:

    • Only validates public properties. Use PropertyOptional for non-existent properties:
      #[v\PropertyOptional('metadata', v\arrayType())] public ?array $metadata;
      
  7. Short-Circuiting:

    • Stops at the first failure. Use allOf() or anyOf() for parallel validation:
      v::allOf(
          v::key('email', v::email()),
          v::key('phone', v::phoneNumber())
      );
      

Debugging Tips

  1. Inspect Results:

    $result = v::email()->validate($input);
    dd($result->getFullMessage()); // Full error tree
    dd($result->getMessages());    // Flat array of messages
    
  2. Enable Debug Mode: Set RESPECT_VALIDATION_DEBUG=1 to see raw validation traces.

  3. Validator Registry: Check registered validators with:

    \Respect\Validation\Validator::getRegistry()->getAll();
    
  4. Symfony Translation: Integrate with Laravel’s translator:

    use Symfony\Contracts\Translation\TranslatorInterface;
    
    $validator = v::email()
        ->setTranslator($app->make(TranslatorInterface::class));
    

Performance Tips

  1. Reuse Validators: Cache frequently used validators (e.g., in a service container):

    $emailValidator = v::email();
    // Reuse $emailValidator across requests.
    
  2. Short-Circuit for Dependent Checks: Avoid validating unrelated fields when possible:

    v::shortCircuit(
        v::key('country', v::countryCode()),
        v::factory(fn($input) => v::key('state', v::subdivisionCode($input['country'])))
    );
    
  3. Avoid allOf/anyOf Overhead: Use all() or any() for lightweight checks:

    v::all(v::numericVal())->validate([1, 2, 3]); // Faster than allOf()
    

Extension Points

  1. Custom Validators:

    • Extend Validator for reusable rules.
    • Use #[Template] for custom error messages:
      #[Template('{{subject}} must be a palindrome')]
      class PalindromeValidator extends Validator {
          public function validate($input) {
              return $input === strrev($input);
          }
      }
      
  2. Custom Formatters: Override NestedListStringFormatter for custom error output:

    use Respect\Validation\Exception\NestedListStringFormatter;
    
    class CustomFormatter extends NestedListStringFormatter {
        protected function formatMessage(string $message): string {
            return strtoupper($message);
        }
    }
    
  3. PSR-11 Container: Register custom validators via a PSR-11 container:

    $container->set(StrongPasswordValidator::class, fn() => new StrongPasswordValidator());
    \Respect\Validation\Validator::setContainer($container);
    
  4. Laravel Service Provider: Bind the validator to Laravel’s container:

    public function register() {
        $this->app->singleton(\Respect\Validation\Validator::class, function () {
            return \Respect\Validation\Validator::create();
        });
    }
    

Migration from v2 to v3

  1. Key Changes:
    • Validator
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony