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 Bundle Laravel Package

braincrafted/validation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require braincrafted/validation-bundle
    

    Enable the bundle in config/bundles.php:

    Braincrafted\Bundle\ValidationBundle\BraincraftedValidationBundle::class => ['all' => true],
    
  2. First Use Case: Validate an enum-like field in a form. For example, restrict a status field to predefined values:

    # config/validation/your_entity.yml
    App\Entity\YourEntity:
        properties:
            status:
                - Braincrafted\Bundle\ValidationBundle\Validator\Constraints\Enum:
                    allowedValues: ["draft", "published", "archived"]
    

Implementation Patterns

Common Workflows

  1. Enum Validation: Use the Enum constraint to validate against a closed set of values (e.g., statuses, roles).

    use Braincrafted\Bundle\ValidationBundle\Validator\Constraints\Enum;
    
    /**
     * @Enum({"active", "inactive", "pending"})
     */
    private $userStatus;
    
  2. Custom Validators: Extend the bundle’s validators by creating custom constraints. For example, validate a string against a regex pattern:

    # config/validation/your_entity.yml
    App\Entity\YourEntity:
        properties:
            slug:
                - Braincrafted\Bundle\ValidationBundle\Validator\Constraints\Regex:
                    pattern: "/^[a-z0-9]+(?:-[a-z0-9]+)*$/"
    
  3. Dynamic Validation: Use the Callback constraint to validate fields dynamically (e.g., check if a username is unique in the database):

    use Symfony\Component\Validator\Constraints\Callback;
    
    /**
     * @Callback(constraints={"callback"="checkUsernameAvailability"})
     */
    private $username;
    
  4. Grouped Validation: Validate subsets of fields based on context (e.g., validate password only if changePassword is true):

    App\Entity\User:
        constraints:
            - Symfony\Component\Validator\Constraints\Valid: ~
        groups: [Default]
        properties:
            changePassword:
                - NotBlank: ~
            password:
                - NotBlank: { groups: ["change_password"] }
    
  5. Integration with Forms: Use the validators in Symfony forms to provide real-time feedback:

    $builder->add('status', EntityType::class, [
        'class' => YourEntity::class,
        'constraints' => [
            new Enum(['active', 'inactive']),
        ],
    ]);
    

Integration Tips

  • Leverage Symfony’s Validation System: The bundle integrates seamlessly with Symfony’s built-in validation. Use it alongside other constraints like NotBlank, Length, or UniqueEntity.

  • Custom Error Messages: Override default error messages in your validation configuration:

    App\Entity\YourEntity:
        properties:
            status:
                - Braincrafted\Bundle\ValidationBundle\Validator\Constraints\Enum:
                    allowedValues: ["draft", "published"]
                    message: "The status '{{ value }}' is not valid. Allowed: draft, published."
    
  • Validation in Services: Use the validator service directly in services or controllers:

    public function updateStatus(Request $request, YourEntity $entity)
    {
        $validator = $this->container->get('validator');
        $errors = $validator->validate($entity, ['status_validation']);
    
        if (count($errors) > 0) {
            // Handle errors
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle: The last release was in 2013, so some features may not work with modern Symfony/Laravel (though Laravel uses Symfony components, this bundle is Symfony2-specific). Test thoroughly in your environment.

  2. Namespace Conflicts: The bundle uses Braincrafted\Bundle\ValidationBundle\Validator\Constraints. Ensure your autoloader includes this namespace or alias it in composer.json:

    "autoload": {
        "psr-4": {
            "Braincrafted\\Bundle\\ValidationBundle\\": "vendor/braincrafted/validation-bundle"
        }
    }
    
  3. Lack of Laravel-Specific Docs: While the bundle works with Symfony’s validator component (used by Laravel), some Laravel-specific quirks (e.g., service container differences) may require adjustments. Use Symfony’s ValidatorInterface directly if needed:

    use Symfony\Component\Validator\Validator\ValidatorInterface;
    $validator = app(ValidatorInterface::class);
    
  4. Validation Groups: If using grouped validation, ensure your entity’s validation groups are properly defined and passed to the validator:

    $validator->validate($entity, ['group_name']);
    

Debugging Tips

  1. Enable Validation Errors: Symfony’s validator throws ConstraintViolationListInterface. Inspect errors like this:

    $errors = $validator->validate($entity);
    foreach ($errors as $error) {
        echo $error->getPropertyPath() . ': ' . $error->getMessage() . PHP_EOL;
    }
    
  2. Check Constraint Parameters: Typos in allowedValues or pattern will silently fail. Validate your YAML/annotations carefully.

  3. Override Constraints: If a validator behaves unexpectedly, create a custom constraint that extends the bundle’s constraints and override logic.


Extension Points

  1. Add Custom Constraints: Extend the bundle by creating new constraints in src/Validator/Constraints and register them in services.yaml:

    services:
        App\Validator\Constraints\CustomConstraint:
            tags: [validator.constraint_validator]
    
  2. Modify Existing Validators: Override the bundle’s validator classes (e.g., EnumValidator) in your project’s src/Validator directory.

  3. Use with Laravel’s Form Requests: Integrate the validators into Laravel’s FormRequest validation:

    public function rules()
    {
        return [
            'status' => ['required', new Enum(['active', 'inactive'])],
        ];
    }
    

    (Note: This requires custom logic to bridge Symfony constraints with Laravel’s validation system.)


Config Quirks

  1. Validation Configuration Files: Place YAML validation files in config/validation/ (Laravel’s convention) or Resources/config/validation.yml (Symfony-style). Ensure the path is correctly referenced in your bundle configuration.

  2. Caching: Symfony’s validator caches constraints. Clear the cache if you update validation rules:

    php artisan cache:clear
    
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views