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

intervention/validation

View on GitHub
Deep Wiki
Context7
## Getting Started
### Minimal Steps
1. **Installation** (unchanged):
   ```bash
   composer require intervention/validation

The package auto-registers via Laravel’s service provider discovery (no manual config needed).

  1. First Use Case (updated with new rules): Validate a VIN number or ISO country code in a form request:

    use Intervention\Validation\Rules\{Vin, CountryCode, CurrencyCode};
    
    $validator = Validator::make($request->all(), [
        'vin' => ['required', new Vin],
        'country' => ['required', new CountryCode],
        'currency' => ['required', new CurrencyCode],
    ]);
    
  2. Where to Look First (updated):

    • New Rule List: README’s Updated Rules (now includes Vin, CountryCode, CurrencyCode, LanguageCode, IetfLanguageTag).
    • Error Messages: Override defaults in resources/lang/{locale}/validation.php (e.g., 'country_code' => 'Invalid ISO-3166 country code.').
    • Rule Documentation: New rules support PHPDoc for IDE hints (e.g., @method bool passes(string $attribute, string $value)).

Implementation Patterns

Core Workflows (updated)

  1. New Rule Application:

    • VIN Validation: Validate vehicle identification numbers (e.g., new Vin).
      'vehicle_vin' => ['required', new Vin],
      
    • Country/Language/Currency Codes: Use for standardized formats:
      'country' => ['required', new CountryCode],
      'language' => ['required', new LanguageCode],
      'currency' => ['required', new CurrencyCode],
      'locale' => ['required', new IetfLanguageTag], // e.g., "en-US"
      
    • Chaining with Native Rules:
      'country' => 'required|country_code|max:2',
      
  2. Form Request Integration (updated example):

    use Intervention\Validation\Rules\{Vin, CountryCode, IetfLanguageTag};
    
    public function rules()
    {
        return [
            'vin' => ['required', new Vin],
            'country' => ['required', new CountryCode],
            'user_locale' => ['required', new IetfLanguageTag],
            'slug' => 'required|slug',
        ];
    }
    
    public function messages()
    {
        return [
            'vin.vin' => 'Invalid VIN format.',
            'country.country_code' => 'Enter a valid 2-letter country code (e.g., US, DE).',
            'user_locale.ietf_language_tag' => 'Invalid language tag (e.g., en-US, fr-CA).',
        ];
    }
    
  3. Dynamic Validation (updated):

    • Conditional Country Codes:
      $validator->sometimes('country', 'country_code', function ($input) {
          return $input->has('international_shipping');
      });
      
    • Locale-Specific Rules: Combine with app()->getLocale() for dynamic validation:
      $validator->after(function ($validator) {
          $validator->sometimes('currency', 'currency_code', fn () => app()->getLocale() === 'en');
      });
      
  4. Testing (updated):

    • Test new rules in isolation:
      $validator = Validator::make(['vin' => '1HGCM82633A123456'], ['vin' => new Vin]);
      $this->assertTrue($validator->passes());
      
      $validator = Validator::make(['country' => 'XYZ'], ['country' => new CountryCode]);
      $this->assertFalse($validator->passes());
      

Integration Tips (updated)

  • API Responses: Leverage new rules for structured data validation (e.g., CountryCode for geolocation APIs).
  • Frontend Sync: Mirror new rule names in frontend validation (e.g., country_code, currency_code).
  • Custom Rule Extensions: Subclass new rules to add constraints:
    class StrictCountryCode extends CountryCode {
        public function passes($attribute, $value) {
            return parent::passes($attribute, strtoupper($value));
        }
    }
    

Gotchas and Tips

Pitfalls (updated)

  1. Case Sensitivity (expanded):

    • Rules like CountryCode/CurrencyCode are case-insensitive by default but may vary (e.g., Vin is case-sensitive).
    • Fix: Normalize input or document expectations:
      $request->merge(['country' => strtoupper($request->country)]);
      
  2. VIN Validation Quirks:

    • Requires 17-character format. Partial VINs (e.g., 10 chars) will fail.
    • Tip: Use sometimes() for optional fields:
      'partial_vin' => ['sometimes', new Vin(['allow_partial' => true])],
      
    • Note: Partial validation is not natively supported; extend the rule if needed.
  3. IETF Language Tag Complexity:

    • Supports formats like en-US, fr-CA, or zh-Hans-CN. Overly complex tags (e.g., en-US-u-ca-islamic) may fail.
    • Debug Tip: Use preg_match('/^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/', $value) to validate manually.
  4. Performance:

    • Rules like Vin involve regex checks. Cache results for repeated validations:
      $vinCache = Cache::remember("vin_{$request->vin}", now()->addHours(1), fn () => new Vin);
      
  5. Deprecation (unchanged):

    • Laravel 10+ only. Avoid mixing with older versions.

Debugging (updated)

  • Rule Failures: Inspect new error keys:
    dd($validator->errors()->messages());
    // Output: ['vin' => ['Invalid VIN format.']]
    
  • Regex Rules: Test patterns separately:
    $pattern = (new Vin)->getRegex();
    var_dump(preg_match($pattern, '1HGCM82633A123456')); // bool(true)
    

Extension Points (updated)

  1. Custom Rule Parameters:

    • Extend CountryCode to allow specific regions:
      class RegionCountryCode extends CountryCode {
          public function __construct(array $allowedRegions = ['EU', 'NA']) {
              $this->allowedRegions = $allowedRegions;
          }
      
          public function passes($attribute, $value) {
              $isValidCountry = parent::passes($attribute, $value);
              $country = $this->getCountryCode($value);
              return $isValidCountry && in_array($this->getRegion($country), $this->allowedRegions);
          }
      }
      
  2. Parameterized VIN Validation:

    • Add support for partial VINs:
      class FlexibleVin extends Vin {
          protected $allowPartial = false;
      
          public function __construct(bool $allowPartial = false) {
              $this->allowPartial = $allowPartial;
          }
      
          public function passes($attribute, $value) {
              if ($this->allowPartial && strlen($value) < 17) {
                  return $this->validatePartial($value);
              }
              return parent::passes($attribute, $value);
          }
      }
      
  3. Testing Extensions:

    • Test new rule parameters:
      public function testFlexibleVin()
      {
          $validator = Validator::make(['vin' => '1HGCM8'], ['vin' => new FlexibleVin(true)]);
          $this->assertTrue($validator->passes());
      }
      

Pro Tips (updated)

  • Batch Validation: Use new rules for bulk data checks (e.g., CountryCode for user imports):
    $users = User::whereNull('country')->get();
    foreach ($users as $user) {
        $validator = Validator::make(['country' => $user->country], ['country' => new CountryCode]);
        if ($validator->fails()) {
            $user->update(['country' => null]);
        }
    }
    
  • Localization: Override messages for new rules per locale (e.g., validation.es.php):
    'country_code' => 'El código de país debe ser válido (ej. ES, US).',
    'vin' => 'El VIN debe tener 17 caracteres.',
    
  • Documentation: Add PHPDoc to new rules for IDE support:
    /**
     * Validate a VIN (Vehicle Identification Number).
     *
     * @param string $attribute
     * @param string $value
     * @return bool
     * @throws \InvalidArgumentException
     */
    
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
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