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

    composer require intervention/validation
    
    • No manual configuration required for Laravel 10+ (auto-discovery enabled).
  2. First Use Case Validate a credit card number in a form request:

    use Intervention\Validation\Rules\Creditcard;
    
    $validator = Validator::make($request->all(), [
        'card_number' => ['required', new Creditcard],
    ]);
    
  3. Where to Look First

    • Documentation: GitHub README (lists all 37 rules).
    • Rule Classes: Browse vendor/intervention/validation/src/Rules/ for rule-specific examples (e.g., Iban.php, Isbn.php).
    • Error Messages: Localized messages are auto-loaded via Laravel’s validation system.

Implementation Patterns

Core Workflows

  1. Inline Rule Usage

    // In a FormRequest or Controller
    $validator = Validator::make($data, [
        'iban' => ['required', new \Intervention\Validation\Rules\Iban],
        'isbn' => ['nullable', new \Intervention\Validation\Rules\Isbn],
    ]);
    
  2. Customizing Rules

    • Parameters: Pass arguments to rules (e.g., country for IBAN):
      new \Intervention\Validation\Rules\Iban('DE') // Validate German IBANs
      
    • Custom Messages: Override defaults:
      $validator->setCustomMessages([
          'iban' => [
              'iban' => 'The :attribute must be a valid IBAN for Germany.',
          ],
      ]);
      
  3. Form Request Integration

    use Intervention\Validation\Rules\Hexadecimalcolor;
    
    public function rules()
    {
        return [
            'hex_color' => ['sometimes', new Hexadecimalcolor],
        ];
    }
    
  4. Batch Validation

    • Useful for APIs or bulk operations:
      $validator = Validator::makeEach($request->all(), [
          '*.iban' => new \Intervention\Validation\Rules\Iban,
          '*.credit_card' => new \Intervention\Validation\Rules\Creditcard,
      ]);
      
  5. Dynamic Rule Application

    • Conditionally apply rules based on request data:
      $rules = ['email' => 'required|email'];
      if ($request->has('is_admin')) {
          $rules['iban'] = new \Intervention\Validation\Rules\Iban;
      }
      Validator::make($request->all(), $rules);
      

Integration Tips

  • Laravel 10+: Leverage auto-discovery for seamless integration.
  • Testing: Use ValidationTestCase or mock Validator facade:
    $validator = Validator::make(['iban' => 'DE89370400440532013000'], [
        'iban' => new \Intervention\Validation\Rules\Iban,
    ]);
    $this->assertTrue($validator->passes());
    
  • API Responses: Pair with Laravel’s ValidatedData or FailedValidationException:
    try {
        $validated = $request->validate([
            'isbn' => new \Intervention\Validation\Rules\Isbn,
        ]);
    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json($e->errors(), 422);
    }
    

Gotchas and Tips

Pitfalls

  1. Rule Naming Collisions

    • Avoid naming conflicts with Laravel’s built-in rules (e.g., hexadecimalcolor vs. hex_color). Use fully qualified class names:
      new \Intervention\Validation\Rules\Hexadecimalcolor // Explicit
      
  2. Locale-Specific Rules

    • Some rules (e.g., Iban, Phone) require country/region parameters. Omitting them may lead to silent failures or broad validations:
      // ❌ Ambiguous (may validate any country)
      new \Intervention\Validation\Rules\Iban
      // ✅ Explicit
      new \Intervention\Validation\Rules\Iban('US')
      
  3. Performance with Complex Rules

    • Rules like Creditcard or Isbn may involve regex or external checks. Test under load if validating thousands of records.
  4. Deprecated Laravel Versions

    • The package is updated for Laravel 10+. If using an older version, check compatibility or fork the package.

Debugging

  • Error Messages: Localized messages are included, but custom overrides may be needed for specific locales.
    // Override all messages for a rule
    $validator->setCustomMessages([
        'iban.iban' => 'Invalid IBAN format.',
    ]);
    
  • Rule Logic: Inspect rule classes (e.g., vendor/intervention/validation/src/Rules/Creditcard.php) for edge cases or custom logic.
  • Validation Events: Use Laravel’s validating or failed events to log or transform data:
    Validator::extend('iban', function ($attribute, $value, $parameters) {
        // Custom logic
        return true;
    });
    

Extension Points

  1. Custom Rules Extend the package by creating a new rule class (e.g., App\Rules\CustomValidation):

    use Intervention\Validation\Rules\AbstractRule;
    class CustomValidation extends AbstractRule {
        public function passes($attribute, $value) {
            return str_contains($value, 'custom');
        }
    }
    

    Register it in AppServiceProvider:

    Validator::extend('custom', 'App\Rules\CustomValidation');
    
  2. Rule Parameters Modify how parameters are parsed in rules (e.g., for Phone validation):

    new \Intervention\Validation\Rules\Phone('US', 'mobile')
    
  3. Testing

    • Mock rules in unit tests:
      $this->partialMock(\Intervention\Validation\Rules\Creditcard::class, function ($mock) {
          $mock->shouldReceive('passes')->andReturn(true);
      });
      
    • Use ValidationTestCase for integration tests.
  4. Configuration

    • No central config file, but you can publish the package’s assets (if available) or override messages in resources/lang/.

Pro Tips

  • Chaining Rules: Combine with Laravel’s built-in rules for complex logic:
    new \Intervention\Validation\Rules\Iban | 'max:34'
    
  • API Documentation: Generate OpenAPI/Swagger docs with validated rules:
    /**
     * @OA\Parameter(
     *     name="iban",
     *     in="query",
     *     required=true,
     *     @OA\Schema(type="string", format="iban")
     * )
     */
    
  • Frontend Validation: Use the same rule names in frontend frameworks (e.g., Vue/VeeValidate) for consistency:
    // VeeValidate example
    this.$validator.extend('iban', {
        validate: value => /^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/i.test(value),
        message: 'Invalid IBAN format.'
    });
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware