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

ajgl/validator-es

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package via Composer:

composer require ajgl/validator-es

First Use Case: Validate a Spanish DNI in a Laravel form request.

  1. Create a custom validation rule:

    // app/Rules/SpanishDniRule.php
    namespace App\Rules;
    
    use Ajgl\ValidatorEs\DniValidator;
    use Illuminate\Contracts\Validation\Rule;
    
    class SpanishDniRule implements Rule
    {
        public function passes($attribute, $value)
        {
            $validator = new DniValidator();
            return $validator->isValid($value);
        }
    
        public function message()
        {
            return 'The :attribute must be a valid Spanish DNI.';
        }
    }
    
  2. Use the rule in a FormRequest:

    // app/Http/Requests/StoreUserRequest.php
    public function rules()
    {
        return [
            'dni' => ['required', new \App\Rules\SpanishDniRule],
        ];
    }
    
  3. Test with valid/invalid inputs:

    $this->post('/users', [
        'dni' => '12345678A', // Valid
    ])->assertValid();
    
    $this->post('/users', [
        'dni' => '12345678B', // Invalid
    ])->assertInvalid(['dni' => 'The dni must be a valid Spanish DNI.']);
    

Key Files to Reference:

  • vendor/ajgl/validator-es/src/ for validator classes.
  • tests/ (if added in future versions) for edge cases.

Implementation Patterns

1. Laravel Integration Patterns

A. Custom Validation Rules (Recommended)

Wrap each validator in a Laravel Rule for seamless integration with FormRequest and API validation.

Example for NIE:

// app/Rules/SpanishNieRule.php
namespace App\Rules;

use Ajgl\ValidatorEs\NieValidator;
use Illuminate\Contracts\Validation\Rule;

class SpanishNieRule implements Rule
{
    public function passes($attribute, $value)
    {
        $validator = new NieValidator();
        return $validator->isValid($value);
    }

    public function message()
    {
        return 'The :attribute must be a valid Spanish NIE.';
    }
}

Usage:

// In FormRequest or Controller
'nie' => ['required', new \App\Rules\SpanishNieRule],

B. Service Layer for Business Logic

Centralize validation logic in a service for reusable business rules (e.g., user onboarding, payment processing).

Example:

// app/Services/SpanishIdValidatorService.php
namespace App\Services;

use Ajgl\ValidatorEs\ValidatorInterface;

class SpanishIdValidatorService
{
    public function validateIdCard(string $idCard): bool
    {
        $validator = new \Ajgl\ValidatorEs\IdCardValidator();
        return $validator->isValid($idCard);
    }

    public function validateSpanishIban(string $iban): bool
    {
        $validator = new \Ajgl\ValidatorEs\IbanValidator();
        return $validator->isValid($iban);
    }
}

Usage in Controller:

public function store(Request $request)
{
    $validator = app(SpanishIdValidatorService::class);
    if (!$validator->validateIdCard($request->dni)) {
        return back()->withErrors(['dni' => 'Invalid ID card.']);
    }
    // Proceed with logic...
}

C. API Response Validation

Use the validators in API responses to ensure data integrity before processing.

Example:

// app/Http/Controllers/UserController.php
public function store(Request $request)
{
    $request->validate([
        'dni' => ['required', new \App\Rules\SpanishDniRule],
        'iban' => ['required', new \App\Rules\SpanishIbanRule],
    ]);

    // Process validated data...
}

2. Workflow Patterns

A. Form Validation

  • Registration Forms: Validate DNI/NIE during user signup.
  • Profile Updates: Re-validate IDs if users edit their details.
  • Multi-Step Forms: Validate IDs early to fail fast (e.g., step 1 of 3).

Example (Laravel Livewire):

// app/Http/Livewire/UserRegistration.php
protected $rules = [
    'dni' => ['required', new \App\Rules\SpanishDniRule],
];

public function updatedDni()
{
    $this->validateOnly('dni');
}

B. API Payload Validation

  • Webhooks: Validate Spanish IDs in incoming webhook data (e.g., payment confirmations).
  • Third-Party Data: Sanitize data from external sources (e.g., ERP systems).

Example (Laravel Sanctum):

// app/Http/Middleware/ValidateSpanishIds.php
public function handle(Request $request, Closure $next)
{
    if ($request->has('user.dni')) {
        $validator = new \Ajgl\ValidatorEs\DniValidator();
        if (!$validator->isValid($request->user['dni'])) {
            return response()->json(['error' => 'Invalid DNI'], 422);
        }
    }
    return $next($request);
}

C. Database Operations

  • Model Observers: Validate IDs before saving to the database.
  • Migration Data: Ensure seed data uses valid Spanish IDs.

Example (Observer):

// app/Observers/UserObserver.php
public function creating(User $user)
{
    $validator = new \Ajgl\ValidatorEs\DniValidator();
    if (!$validator->isValid($user->dni)) {
        throw new \InvalidArgumentException('Invalid DNI format.');
    }
}

3. Testing Patterns

A. Unit Testing Validators

Test the wrapper rules to ensure they delegate correctly to the underlying validators.

Example:

// tests/Unit/Rules/SpanishDniRuleTest.php
public function test_dni_validation()
{
    $rule = new \App\Rules\SpanishDniRule();

    $this->assertTrue($rule->passes('dni', '12345678A'));
    $this->assertFalse($rule->passes('dni', '12345678B'));
}

B. Feature Testing

Test validation in the context of user flows (e.g., registration, profile updates).

Example (Registration Flow):

// tests/Feature/UserRegistrationTest.php
public function test_dni_validation_on_registration()
{
    $response = $this->post('/register', [
        'dni' => '12345678B', // Invalid
        'name' => 'Test User',
    ]);

    $response->assertSessionHasErrors('dni');
}

C. Edge Case Testing

Test edge cases like:

  • Empty strings.
  • Non-string inputs (e.g., null, integers).
  • Historical formats (e.g., old DNI/NIE patterns).

Example:

public function test_edge_cases()
{
    $validator = new \Ajgl\ValidatorEs\DniValidator();

    $this->assertFalse($validator->isValid(''));
    $this->assertFalse($validator->isValid(null));
    $this->assertFalse($validator->isValid(12345678)); // Non-string
}

Gotchas and Tips

Pitfalls

  1. Case Sensitivity in NIE/DNI:

    • The validator expects uppercase letters (e.g., 71234567Z, not 71234567z).
    • Fix: Normalize input before validation:
      $dni = strtoupper($request->dni);
      
  2. IBAN Limitations:

    • The IbanValidator only supports Spanish IBANs (e.g., ESXXXXXX).
    • Fix: Add a prefix check or custom rule if accepting international IBANs:
      if (!str_starts_with($iban, 'ES')) {
          return false;
      }
      
  3. CCC Validation Quirks:

    • The CccValidator may reject valid CCC codes if they include non-numeric characters (e.g., spaces, hyphens).
    • Fix: Sanitize input:
      $ccc = preg_replace('/[^0-9]/', '', $request->ccc);
      
  4. No Real-Time Verification:

    • This package only validates format, not whether the ID exists in government databases.
    • Fix: Combine with an external API (e.g., Spanish tax agency) for real-time checks.
  5. Deprecated Methods:

    • Older versions may use deprecated parent classes (e.g., Symfony\Component\Validator\Validator).
    • Fix: Update to the latest version (ajgl/validator-es:^0.1.6).
  6. No Custom Error Messages:

    • The underlying validators return true/false without context.
    • Fix: Extend the wrapper to provide detailed feedback:
      public
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle