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

joepc74/laravel-spanish-validator

Laravel package that provides Spanish-language validation messages for Laravel’s validator, helping you localize form errors quickly. Drop in, configure the locale, and use standard Laravel validation rules with Spanish responses.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require joepc74/laravel-spanish-validator
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Joepc74\SpanishValidator\SpanishValidatorServiceProvider"
    
  2. Basic Usage Validate a Spanish NIF (Tax ID):

    use Joepc74\SpanishValidator\Facades\SpanishValidator;
    
    $isValid = SpanishValidator::validateNIF('12345678A');
    
  3. First Use Case Add validation rules to a Laravel form request:

    use Illuminate\Validation\Rule;
    
    public function rules()
    {
        return [
            'nif' => ['required', Rule::unique('users')->ignore($this->user),
                      function ($attribute, $value, $fail) {
                          if (!SpanishValidator::validateNIF($value)) {
                              $fail('El NIF no es válido.');
                          }
                      }]
        ];
    }
    

Implementation Patterns

Validation Workflows

  1. Form Requests Reuse the validator in multiple requests:

    public function rules()
    {
        return [
            'nie' => ['required', function ($value) {
                return SpanishValidator::validateNIE($value);
            }],
            'cif' => ['required', function ($value) {
                return SpanishValidator::validateCIF($value);
            }],
        ];
    }
    
  2. API Responses Return structured validation errors:

    try {
        SpanishValidator::validateIBAN($request->iban);
    } catch (\InvalidArgumentException $e) {
        return response()->json(['error' => 'IBAN inválido'], 422);
    }
    
  3. Custom Rules Extend Laravel’s Rule class for reusable validation:

    use Joepc74\SpanishValidator\Facades\SpanishValidator;
    
    class ValidSpanishNSS extends Rule
    {
        public function passes($attribute, $value)
        {
            return SpanishValidator::validateNSS($value);
        }
    }
    

Integration Tips

  • Localization: Use Laravel’s trans() helper for multilingual error messages.
  • Testing: Mock the validator in unit tests:
    $validator = Mockery::mock('alias:SpanishValidator');
    $validator->shouldReceive('validateNIF')->once()->andReturn(true);
    
  • Frontend Validation: Return validation rules via API for frontend frameworks (e.g., Vue/React).

Gotchas and Tips

Pitfalls

  1. Case Sensitivity

    • NIF/NIE letters are case-sensitive (e.g., '12345678A' is valid, '12345678a' may fail).
    • Fix: Normalize input:
      $nif = strtoupper($request->nif);
      
  2. IBAN Validation Quirks

    • Some IBANs (e.g., from older banks) may fail due to strict formatting.
    • Tip: Use SpanishValidator::validateIBAN($iban, false) to skip strict checks.
  3. Phone Number Formats

    • Spanish numbers can include spaces, hyphens, or + prefixes.
    • Tip: Sanitize input:
      $cleanPhone = preg_replace('/[^0-9]/', '', $request->phone);
      

Debugging

  • Invalid NIF/NIE: Check the letter against the control digit algorithm.
  • CIF Errors: Ensure the format matches ABC1234567 or 12345678 (legal entities vs. individuals).
  • Postal Code: Validate with SpanishValidator::validatePostalCode(); Spanish codes are 5 digits (e.g., 28001).

Extension Points

  1. Custom Validation Logic Override the service provider to add business rules:

    SpanishValidator::extend('customNIF', function ($nif) {
        return SpanishValidator::validateNIF($nif) && str_starts_with($nif, '123');
    });
    
  2. Configuration Modify published config (config/spanish-validator.php) to adjust:

    • Allowed NIE prefixes (e.g., X, Y, Z for foreigners).
    • Phone number regex patterns.
  3. Performance For bulk validation (e.g., CSV imports), cache results:

    $cacheKey = 'nif_'.$nif;
    if (!cache()->has($cacheKey)) {
        cache()->put($cacheKey, SpanishValidator::validateNIF($nif), 60);
    }
    
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