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

milwad/laravel-validate

Enhanced Laravel validation with a large set of custom rule classes and helper methods for faster, cleaner advanced validation. Includes localization support and works with Laravel 9+ (PHP 8+), with community-contributed language packs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require milwad/laravel-validate
    

    Publish config (optional):

    php artisan vendor:publish --tag="laravel-validate-config"
    
  2. First Use Case: Validate a phone number in a Form Request:

    use Milwad\LaravelValidate\Rules\ValidPhoneNumber;
    
    public function rules()
    {
        return [
            'phone' => ['required', new ValidPhoneNumber()],
        ];
    }
    
  3. Quick Validation: Use built-in rules directly in validation arrays:

    $validator = Validator::make($data, [
        'email' => 'required|email',
        'credit_card' => 'required|ValidCreditCard',
    ]);
    

Where to Look First

  • Rules Table in the README for available validators.
  • Documentation for rule-specific details (e.g., ValidJwt, ValidIban).
  • Published Config (config/laravel-validate.php) to enable using_container for string-based rule syntax.

Implementation Patterns

Core Workflows

  1. Rule Instantiation:

    • Object Syntax (Recommended for clarity):
      $rules = [
          'field' => [new ValidEmail(), new ValidDomain()],
      ];
      
    • String Syntax (Requires using_container: true in config):
      $rules = [
          'field' => 'required|ValidEmail|ValidDomain',
      ];
      
  2. Dynamic Rule Parameters: Pass arguments to rules via with() or constructor:

    // Using constructor
    new ValidLength(10, 20)
    
    // Using with() (for rules supporting it)
    (new ValidLength())->with(10, 20)
    
  3. Custom Rule Extension: Extend Milwad\LaravelValidate\Rules\BaseRule for reusable logic:

    use Milwad\LaravelValidate\Rules\BaseRule;
    
    class ValidCustomFormat extends BaseRule {
        public function passes($attribute, $value) {
            return preg_match('/^your_pattern$/', $value);
        }
    }
    
  4. Localization: Publish language files for custom messages:

    php artisan vendor:publish --tag="validate-lang-en"
    

    Override messages in resources/lang/en/validation.php:

    'valid_custom_format' => 'The :attribute must match the custom format.',
    
  5. Form Request Integration: Combine with Laravel’s Form Requests for DRY validation:

    public function rules()
    {
        return [
            'username' => ['required', new ValidDiscordUsername()],
            'iban' => ['required', new ValidIban()],
        ];
    }
    
    public function messages()
    {
        return [
            'username.ValidDiscordUsername' => 'Invalid Discord username format.',
        ];
    }
    
  6. API Validation: Use in API resources or controllers:

    public function store(Request $request) {
        $validated = $request->validate([
            'token' => ['required', new ValidJwt()],
            'ip' => ['required', 'ValidIpAddressIPV4'],
        ]);
    }
    
  7. Testing: Test rules in PHPUnit:

    public function test_valid_phone_number()
    {
        $rule = new ValidPhoneNumber();
        $this->assertTrue($rule->passes('phone', '+1234567890'));
        $this->assertFalse($rule->passes('phone', 'invalid'));
    }
    

Integration Tips

  • Leverage Laravel’s Validation Extensibility: Combine with built-in rules (e.g., required|ValidCreditCard|digits:16).
  • Conditional Rules: Use sometimes or optional with custom rules:
    $rules = [
        'field' => ['sometimes', new ValidCustomRule()],
    ];
    
  • Rule Chaining: Chain rules for complex validation:
    $validator = Validator::make($data, [
        'password' => [
            new ValidLength(8),
            new ValidContainsSpecialChars(),
        ],
    ]);
    
  • Service Container Binding: Bind custom rules for dependency injection:
    $this->app->bind('ValidCustomRule', function () {
        return new ValidCustomRule();
    });
    

Gotchas and Tips

Pitfalls

  1. using_container Misconfiguration:

    • Issue: String rules (e.g., ValidPhone) fail if using_container is false.
    • Fix: Set 'using_container' => true in config/laravel-validate.php or use object syntax.
    • Debug: Check config('laravel-validate.using_container') in a Tinker session.
  2. Rule Parameter Order:

    • Some rules (e.g., ValidLength) require parameters in a specific order. Incorrect order may cause silent failures.
    • Tip: Refer to the documentation for parameter order.
  3. Localization Overrides:

    • Custom messages may not reflect changes if cached. Clear the view cache:
      php artisan view:clear
      
    • Tip: Use php artisan config:clear if config changes aren’t applied.
  4. Case Sensitivity in Rules:

    • Rule class names are case-sensitive (e.g., ValidPhoneNumber vs. validphonenumber).
    • Tip: Use IDE autocompletion to avoid typos.
  5. Performance with Complex Rules:

    • Rules like ValidDuplicate or ValidIban may involve heavy computations (e.g., regex, API calls).
    • Tip: Cache results for repeated validations or use sometimes to skip when unnecessary.
  6. Dependency Conflicts:

    • Some rules (e.g., ValidJwt) may require additional libraries (e.g., firebase/php-jwt).
    • Tip: Check the documentation for dependencies.
  7. Testing Edge Cases:

    • Rules may fail on edge cases (e.g., empty strings, null values). Test with:
      $this->assertFalse($rule->passes('field', null));
      $this->assertFalse($rule->passes('field', ''));
      

Debugging Tips

  • Enable Debug Mode: Add this to your AppServiceProvider to log validation errors:

    Validator::extend('custom', function ($attribute, $value, $parameters, $validator) {
        \Log::debug("Validating $attribute with value: $value");
        return true; // or false
    });
    
  • Inspect Rule Logic: Temporarily modify the passes() method in custom rules to add debug logs:

    public function passes($attribute, $value) {
        \Log::debug("Validating $attribute: $value");
        return preg_match('/pattern/', $value);
    }
    
  • Check Published Config: Verify config/laravel-validate.php after publishing:

    php artisan config:clear
    

Extension Points

  1. Custom Rule Attributes: Extend Milwad\LaravelValidate\Rules\BaseRule to add custom attributes:

    class ValidCustomAttribute extends BaseRule {
        public function __construct($attribute) {
            $this->attribute = $attribute;
        }
    
        public function passes($attribute, $value) {
            return $value === $this->attribute;
        }
    }
    

    Usage:

    new ValidCustomAttribute('expected_value')
    
  2. Dynamic Rule Factories: Create a factory for rules with dynamic parameters:

    class RuleFactory {
        public static function validLength($min, $max) {
            return new ValidLength($min, $max);
        }
    }
    

    Usage:

    $rules = [
        'field' => [RuleFactory::validLength(5, 10)],
    ];
    
  3. Rule Collections: Group related rules for reuse:

    class UserRules {
        public static function getRules() {
            return [
                'email' => ['required', 'email'],
                'phone' => [new ValidPhoneNumber()],
            ];
        }
    }
    

    Usage:

    $validator = Validator::make($data, UserRules::getRules());
    
  4. Rule Events: Listen to validation events to log or modify rules:

    Validator::extend('custom', function () {
        event(new Validating());
        return true;
    });
    
  5. Rule Testing Utilities: Create a trait for testing rules:

    trait TestsRules {
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor