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

Validator Bundle Laravel Package

assoconnect/validator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require assoconnect/validator-bundle
    

    Accept the Symfony Flex recipe when prompted (y or p for permanent).

  2. First Use Case: Validate an email field in an entity:

    use AssoConnect\ValidatorBundle\Validator\Constraint as AssoConnectAssert;
    
    class User
    {
        #[AssoConnectAssert\Email()]
        public string $email;
    }
    
  3. Where to Look First:

    • Documentation for constraint options and examples.
    • Constraint Classes for available validators (e.g., EmailValidator.php, FrenchSirenValidator.php).
    • Release Notes for breaking changes (e.g., Symfony 7.0+ support, PHP 8.4+ requirement).

Implementation Patterns

Core Workflows

1. Basic Validation

Apply constraints directly to entity properties:

class Order
{
    #[AssoConnectAssert\Money(min: 0.01, max: 10000)]
    public float $amount;

    #[AssoConnectAssert\Timezone()]
    public string $timezone;
}

2. Doctrine Auto-Validation

Use @Entity() to auto-apply validators based on Doctrine types:

#[AssoConnectAssert\Entity()]
class BankAccount
{
    #[ORM\Column(type: 'iban')]
    public string $iban; // Auto-validates as `@Iban()`, `@Length(27)`, etc.
}

3. Customizing Auto-Validation

Extend EntityValidator to override defaults:

class CustomEntityValidator extends EntityValidator
{
    protected function getConstraintsForType(string $type): array
    {
        return match ($type) {
            'iban' => [new Assert\Iban(), new Assert\Length(34)],
            default => parent::getConstraintsForType($type),
        };
    }
}

Register the validator in services.yaml:

services:
    App\Validator\Constraints\CustomEntityValidator:
        tags: [validator.constraint_validator]

4. Dynamic Validation

Use constraints with runtime parameters:

#[AssoConnectAssert\Phone(countryCode: 'FR')]
public string $phone;

5. Form Validation

Integrate with Symfony Forms:

$builder->add('email', EmailType::class, [
    'constraints' => [new AssoConnectAssert\Email()],
]);

Integration Tips

  • Symfony 7+: Ensure your project uses Symfony 7.0+ (minimum requirement).
  • PHP 8.4+: The bundle requires PHP 8.4+ (check composer.json).
  • Doctrine ORM: Auto-validation works best with Doctrine entities (e.g., iban, email types).
  • Testing: Use ValidatorInterface in tests:
    $validator = $container->get('validator');
    $errors = $validator->validate($entity);
    

Gotchas and Tips

Pitfalls

  1. Symfony Version Mismatch:

    • The bundle drops Symfony 6.x support (v2.39.0+). Ensure your project uses Symfony 7.0+.
    • Fix: Downgrade to v2.38.0 if stuck on Symfony 6.4.
  2. PHP Version Requirements:

    • Requires PHP 8.4+ (v2.42.0+). Older versions may fail.
    • Fix: Use v2.39.0 for PHP 8.3 support.
  3. Doctrine Auto-Validation Limitations:

    • @Entity() only works for Doctrine-mapped properties. Non-Doctrine properties require manual constraints.
    • Tip: Combine with @Assert\Type() for non-Doctrine fields.
  4. Constraint Overrides:

    • Custom validators must implement ConstraintValidatorInterface and be tagged in services.yaml.
    • Example:
      services:
          App\Validator\Constraints\CustomEmailValidator:
              tags: [validator.constraint_validator]
      
  5. Deprecated Annotations:

    • The bundle supports both annotations and attributes (since v2.26), but annotations are deprecated in favor of attributes.
    • Tip: Use attributes (#[AssoConnectAssert\Email()]).
  6. Timezone Validation:

    • The Timezone validator uses PHP’s DateTimeZone class. Invalid timezones (e.g., "America/New_York" vs. "Invalid/Zone") will fail silently unless you add a custom message:
      #[AssoConnectAssert\Timezone(message: 'The timezone "{{ value }}" is invalid.')]
      
  7. French SIREN/SIRET:

    • These validators enforce strict formats. Partial or malformed numbers (e.g., 1234567890123 vs. 12345678901234) will fail.
    • Tip: Use #[AssoConnectAssert\FrenchSiren(message: 'Invalid SIREN format.')] for custom messages.

Debugging Tips

  1. Validator Not Triggering:

    • Ensure the constraint is tagged in services.yaml:
      services:
          AssoConnect\ValidatorBundle\Validator\Constraints\EmailValidator:
              tags: [validator.constraint_validator]
      
    • Debug: Check Symfony’s profiler under "Validation" > "Errors" to see unapplied constraints.
  2. Custom Validator Not Working:

    • Verify the validator class implements ConstraintValidatorInterface.
    • Debug: Use dump($validator->validate($value)) to inspect validation logic.
  3. Doctrine Auto-Validation Failing:

    • Ensure the property has a Doctrine type (e.g., type: 'iban').
    • Debug: Temporarily add manual constraints to isolate the issue.
  4. Performance Issues:

    • The @Entity() constraint validates all properties on every call. For large entities, manually apply constraints to critical fields.
    • Tip: Use #[AssoConnectAssert\Entity(skipProperties: ['nonCriticalField'])].

Extension Points

  1. Add New Validators:

    • Extend AbstractValidator and register the service:
      class CustomNifValidator extends AbstractValidator
      {
          public function validate($value, Constraint $constraint)
          {
              // Custom logic
          }
      }
      
      services:
          App\Validator\Constraints\CustomNifValidator:
              tags: [validator.constraint_validator]
      
  2. Override Existing Constraints:

    • Create a custom constraint class (e.g., CustomEmail) and validator, then replace the default in services.yaml:
      services:
          AssoConnect\ValidatorBundle\Validator\Constraints\EmailValidator:
              class: App\Validator\Constraints\CustomEmailValidator
      
  3. Add Custom Messages:

    • Pass message directly in the constraint:
      #[AssoConnectAssert\Phone(message: 'Invalid phone number for {{ countryCode }}.')]
      
  4. Integrate with API Platform:

    • Use the bundle’s constraints in API Platform’s #[ApiProperty]:
      #[ApiProperty(constraints: [new AssoConnectAssert\Email()])]
      public string $email;
      

Pro Tips

  • Combine with Symfony’s Built-ins: Use the bundle alongside Symfony’s native constraints (e.g., @Assert\NotBlank()):

    #[Assert\NotBlank]
    #[AssoConnectAssert\Email]
    public string $email;
    
  • Validation Groups: Apply constraints to specific groups (e.g., Default, Registration):

    #[AssoConnectAssert\Email(groups: ['Registration'])]
    public string $email;
    
  • Bulk Validation: Validate collections with ValidatorInterface::validate():

    $validator->validateValue($users, new Assert\All([
        new AssoConnectAssert\Email(),
    ]));
    
  • Localization: Customize error messages in validation.yaml:

    constraints:
        AssoConnect\ValidatorBundle\Validator\Constraint\Email:
            message: 'L''adresse email "{{ value }}" est invalide.'
    
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