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

Dateformat To Regex Laravel Package

apie/dateformat-to-regex

Converts PHP date() format strings into “simple” regular expressions for validating date/time strings. Generates regex that matches the format pattern (not full calendar validation, e.g., may accept 30 February). Includes a static DateFormatToRegex::formatToRegex() helper.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require apie/dateformat-to-regex
    

    Ensure your Laravel project uses PHP 8.3+ (required by the package).

  2. First Use Case: Convert a Laravel Carbon date format (e.g., Y-m-d) to a regex for validation:

    use Apie\DateformatToRegex\DateFormatToRegex;
    use Carbon\Carbon;
    
    $format = Carbon::DEFAULT_TO_STRING_FORMAT; // 'Y-m-d H:i:s'
    $regex = DateFormatToRegex::formatToRegex($format);
    
    // Validate a string (e.g., from user input)
    $isValid = (bool) preg_match($regex, '2024-05-20 14:30:00');
    
  3. Where to Look First:

    • README.md for basic usage.
    • Monorepo docs for advanced features (e.g., strict validation).
    • Laravel’s Carbon docs for date format strings (e.g., Y-m-d H:i:s).

Implementation Patterns

Core Workflows

  1. Form Request Validation: Use the package to validate date strings in Laravel’s FormRequest:

    use Illuminate\Validation\Rule;
    use Apie\DateformatToRegex\DateFormatToRegex;
    
    public function rules()
    {
        return [
            'event_date' => [
                'required',
                'string',
                function ($attribute, $value, $fail) {
                    $regex = DateFormatToRegex::formatToRegex('Y-m-d');
                    if (!preg_match($regex, $value)) {
                        $fail('The '.$attribute.' format is invalid.');
                    }
                },
            ],
        ];
    }
    
  2. Dynamic Regex Generation: Generate regexes dynamically based on user-selected formats (e.g., in a settings panel):

    $userFormat = $request->input('date_format'); // e.g., 'd/m/Y'
    $regex = DateFormatToRegex::formatToRegex($userFormat);
    
  3. Strict vs. Lenient Validation:

    • Lenient (default): Allows invalid dates (e.g., 30 February).
    • Strict (future feature): Extend the package or use apie/core for strict validation:
      // Hypothetical strict usage (check monorepo for updates)
      $strictRegex = DateFormatToRegex::strictFormatToRegex('Y-m-d');
      

Integration Tips

  • Laravel Blade: Cache regexes in a service container or Blade directive for reuse:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        Blade::directive('dateRegex', function ($format) {
            return "<?php echo preg_match(Apie\\DateformatToRegex\\DateFormatToRegex::formatToRegex({$format}), ?); ?>";
        });
    }
    

    Usage:

    @dateRegex('Y-m-d')($userInput)
    
  • API Responses: Validate incoming API dates with middleware:

    public function handle($request, Closure $next)
    {
        $regex = DateFormatToRegex::formatToRegex('Y-m-d\TH:i:s');
        if (!$request->has('date') || !preg_match($regex, $request->date)) {
            return response()->json(['error' => 'Invalid date format'], 400);
        }
        return $next($request);
    }
    
  • Testing: Mock regex generation in PHPUnit:

    $this->partialMock(DateFormatToRegex::class, ['formatToRegex'])
         ->method('formatToRegex')
         ->willReturn('/^\d{4}-\d{2}-\d{2}$/');
    

Gotchas and Tips

Pitfalls

  1. PHP 8.3 Requirement:

    • Ensure your Laravel project uses PHP 8.3+ (check php -v and composer.json).
    • Fix: Update your Laravel version or use a local PHP 8.3 environment (e.g., Docker).
  2. False Positives:

    • The package’s "simple" regex may match invalid dates (e.g., 30 February).
    • Workaround: Combine with Carbon validation:
      $date = Carbon::createFromFormat($format, $value);
      if (!$date || $date->format($format) !== $value) {
          // Invalid date
      }
      
  3. Monorepo Dependency:

    • The package relies on apie/core (not directly installable via Composer).
    • Tip: Check the monorepo for updates or fork the package to include core functionality.
  4. Edge Cases:

    • Timezones (e.g., Z, e) may not be fully supported in regex.
    • Test: Validate against Carbon::ATOM and Carbon::ISO8601 formats.

Debugging

  • Regex Output: Log the generated regex to debug matches:
    $regex = DateFormatToRegex::formatToRegex('Y-m-d');
    \Log::debug("Generated regex: {$regex}");
    
  • Validation Errors: Use preg_last_error() to diagnose regex issues:
    if (!preg_match($regex, $value)) {
        \Log::error("Regex error: " . preg_last_error());
    }
    

Extension Points

  1. Custom Format Support: Extend the package to handle custom formats (e.g., dddd, D MMMM Y):

    // Fork the package and extend DateFormatToRegex::formatToRegex()
    public static function formatToRegex(string $format): string
    {
        // Add custom rules for 'dddd' (e.g., Monday)
        return parent::formatToRegex($format);
    }
    
  2. Strict Validation: Use apie/core (if available) or implement a wrapper:

    public static function strictFormatToRegex(string $format): string
    {
        $regex = self::formatToRegex($format);
        // Add negative lookahead for invalid dates (e.g., 30 Feb)
        return preg_replace(
            '/\d{2}\s+Feb(ruary)?/',
            '(?!30|31)(?!\b0?[0-9]{2}\b)', // Example: Reject Feb 30-31
            $regex
        );
    }
    
  3. Performance:

    • Cache regexes in Laravel’s cache system:
      $regex = Cache::remember("regex_{$format}", now()->addHours(1), function () use ($format) {
          return DateFormatToRegex::formatToRegex($format);
      });
      

Config Quirks

  • No Config File: The package has no configuration options.
  • Locale Sensitivity: Date formats may behave differently across locales (e.g., MMMM vs. MMM). Test with your app’s locale.
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.
terminal42/code-quality-tools
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