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

Laravel Spanish Validator Laravel Package

orumad/laravel-spanish-validator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require orumad/laravel-spanish-validator
    
  2. Publish config (optional):

    php artisan vendor:publish --provider="Orumad\SpanishValidator\SpanishValidatorServiceProvider" --tag="config"
    

    (Default config works out-of-the-box, but publishing allows customization of regex patterns or error messages.)

  3. First use case: Validate a NIF in a Laravel request:

    use Orumad\SpanishValidator\Rules\Nif;
    
    $request->validate([
        'nif' => ['required', new Nif],
    ]);
    

Where to Look First

  • Rule classes: vendor/orumad/laravel-spanish-validator/src/Rules/ (e.g., Nif.php, Nie.php).
  • Config file: config/spanish-validator.php (after publishing).
  • Tests: tests/ for edge-case examples (e.g., invalid formats, special characters).

Implementation Patterns

Core Workflows

  1. Form Validation:

    $request->validate([
        'tax_id' => ['required', new \Orumad\SpanishValidator\Rules\Cif],
        'phone'  => ['required', 'spanish_phone'],
    ]);
    

    (Use string aliases like spanish_nif, spanish_iban for cleaner code.)

  2. Manual Validation:

    use Orumad\SpanishValidator\Rules\Nss;
    
    $validator = new Nss;
    if ($validator->passes('12345678A')) {
        // Valid NSS
    }
    
  3. Custom Error Messages:

    $request->validate([
        'nie' => ['required', new \Orumad\SpanishValidator\Rules\Nie, 'custom.message'],
    ], [
        'custom.message' => 'The :attribute must be a valid NIE (e.g., X1234567Z).',
    ]);
    

Integration Tips

  • API Responses: Return validation errors with standardized messages:
    $validator = Validator::make($request->all(), [
        'postal_code' => ['required', 'spanish_postal_code'],
    ]);
    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 422);
    }
    
  • Model Rules: Extend Laravel’s FormRequest or Model validation:
    public function rules()
    {
        return [
            'nss' => ['required', new \Orumad\SpanishValidator\Rules\Nss],
        ];
    }
    
  • Dynamic Validation: Use the package in API gateways or middleware:
    public function handle($request, Closure $next)
    {
        if ($request->routeIs('tax-registration') && !$request->hasValid('cif')) {
            abort(422, 'Invalid CIF provided.');
        }
        return $next($request);
    }
    

Advanced Patterns

  • Batch Validation: Validate arrays of IDs (e.g., bulk NIF checks):
    $nifs = ['12345678A', '98765432B'];
    $valid = collect($nifs)->every(fn($nif) => (new \Orumad\SpanishValidator\Rules\Nif)->passes($nif));
    
  • Localization: Override error messages in language files:
    // resources/lang/es/validation.php
    'spanish_nif' => 'El :attribute debe ser un NIF válido (ej. 12345678A).',
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity:

    • NIF/NIE letters (e.g., A, B) are case-insensitive in validation but must match the input’s case for strict checks. Use strtoupper() if consistency is critical:
      $nif = strtoupper($request->nif);
      
    • Exception: The package normalizes input internally, but custom logic may override this.
  2. CIF Quirks:

    • CIFs for companies start with letters AJ (natural persons) or P (entities). The validator checks this, but false positives may occur with malformed inputs (e.g., 123456789).
    • Fix: Add a custom rule to pre-filter alphanumeric strings:
      $request->validate([
          'cif' => ['required', 'string', 'min:9', new \Orumad\SpanishValidator\Rules\Cif],
      ]);
      
  3. IBAN Edge Cases:

    • Spanish IBANs (ESXX) require 24 characters (including ES). The validator enforces this, but copy-pasted IBANs (e.g., with spaces) will fail.
    • Tip: Sanitize input first:
      $iban = preg_replace('/\s+/', '', $request->iban);
      
  4. Postal Code Ambiguity:

    • Spanish postal codes (e.g., 28001) are 5 digits, but some regions use 4 digits (e.g., 38001 for Canary Islands). The validator uses a strict regex by default.
    • Workaround: Extend the rule or use a custom regex:
      $validator = new \Orumad\SpanishValidator\Rules\PostalCode;
      $validator->setRegex('/^\d{4,5}$/'); // Relaxed validation
      
  5. Phone Number Variability:

    • Spanish numbers can include +34, 0034, or no prefix. The validator accepts all formats but may reject valid numbers if the config’s prefix option is misconfigured.
    • Solution: Publish the config and adjust:
      'phone' => [
          'prefix' => '+34', // or null to allow all prefixes
      ],
      

Debugging Tips

  • Log Validation Errors:
    $validator = Validator::make($data, ['nif' => new \Orumad\SpanishValidator\Rules\Nif]);
    \Log::debug('Validation errors:', $validator->errors()->toArray());
    
  • Test Edge Cases: Use the package’s tests as a reference:
    // Example: Test NIE with letters Y, Z (valid for foreigners)
    $nieRule = new \Orumad\SpanishValidator\Rules\Nie;
    $nieRule->passes('Y1234567Z'); // Should return true
    
  • Regex Debugging: For custom rules, inspect the underlying regex:
    $nifRule = new \Orumad\SpanishValidator\Rules\Nif;
    \Log::debug('NIF regex:', $nifRule->getRegex());
    

Extension Points

  1. Custom Rules: Extend the base SpanishValidatorRule class to add domain-specific logic:

    use Orumad\SpanishValidator\Rules\SpanishValidatorRule;
    
    class CustomNif extends SpanishValidatorRule {
        protected function getRegex() {
            return '/^[\d]{8}[A-Z]$/'; // Custom pattern
        }
    }
    
  2. Override Config: Modify the published config to adjust validation strictness:

    // config/spanish-validator.php
    'nif' => [
        'strict_letter_check' => true, // Enforces letter ranges (e.g., J for NIFs)
    ],
    
  3. Add New Validators: Fork the package and add a new rule (e.g., for DNI or NIE with letters X/Y/Z only):

    // src/Rules/NieForeigner.php
    class NieForeigner extends SpanishValidatorRule {
        protected function getRegex() {
            return '/^[XYZ]\d{7}[A-Z]$/';
        }
    }
    
  4. Localization: Override error messages in your app’s language files:

    // resources/lang/en/validation.php
    'spanish_nif' => 'The :attribute must be a valid Spanish NIF (e.g., 12345678A).',
    

Performance Notes

  • Regex Compilation: The package compiles regex patterns once during bootstrapping. For high-throughput systems (e.g., bulk validation), cache the rule instances:
    $cachedNifRule = new \Orumad\SpanishValidator\Rules\Nif;
    foreach ($nifs as $nif) {
        $cachedNifRule->passes($nif);
    }
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle