Installation:
composer require braincrafted/validation-bundle
Enable the bundle in config/bundles.php:
Braincrafted\Bundle\ValidationBundle\BraincraftedValidationBundle::class => ['all' => true],
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"]
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;
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]+)*$/"
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;
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"] }
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']),
],
]);
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
}
}
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.
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"
}
}
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);
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']);
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;
}
Check Constraint Parameters:
Typos in allowedValues or pattern will silently fail. Validate your YAML/annotations carefully.
Override Constraints: If a validator behaves unexpectedly, create a custom constraint that extends the bundle’s constraints and override logic.
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]
Modify Existing Validators:
Override the bundle’s validator classes (e.g., EnumValidator) in your project’s src/Validator directory.
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.)
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.
Caching: Symfony’s validator caches constraints. Clear the cache if you update validation rules:
php artisan cache:clear
How can I help you explore Laravel packages today?