Bastien Donjon

Développeur web à Bordeaux

iso8601 Archive

Friday

27

November 2015

0

COMMENTS

ISO8601 Date validator for Laravel 5

Written by , Posted in PHP

date_format rule for Laravel 5 Validator don’t work.

So here is a validation rule for Laravel :

<?php

// file : app/Provider/AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Validation
        Validator::extend(
            'iso_date',
            function ($attribute, $value, $parameters, $validator) {
                $regex = '/^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|' .
                         '(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]' .
                         '\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)' .
                         '-02-29)T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:Z|[+-][01]\d:[0-5]\d)$/';

                return preg_match_all($regex, $value) > 0;
            }
        );
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Original answer on Stackoverflow