Categories
Laravel 5 PHP

Laravel 5 Cron expression validation

A Cron expression validator is created in Laravel 5.3. Laravel provides a versatile and extendable Validation class. Introducing new validations is done by registering a validation function with the extend method on the Validation facade. A Cron expression validator is created by utilising a cron-expression parser.

The cron-expression parser used here is the fantastic cron-expression Composer package by Michael Dowling.

First, require the Composer package.

composer require mtdowling/cron-expression

Second, extend the Validator-class with a cron_expression validation method in the boot method of an appropriate Service Provider (e.g. AppServiceProvider.php). Don’t forget to import the class:

use Cron\CronExpression;

Then modify the boot function.

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Validator::extend('cron_expression', function ($attribute, $value, $parameters, $validator) {
        return CronExpression::isValidExpression( $value );
    });
}

It is also possible to put this in a separate package (and separate Service Provider).

Finally, add the translation to the appropriate language files (e.g. /resources/lang/en/validation.php):

'cron_expression'      => 'The :attribute field contains no valid CRON expression.',

Use the validator like any other validation rule.

$this->validate($request, [
    'recurrence' => 'required|cron_expression',
    'name' => 'required',
]);

Done already! I enjoy the ease of implementing a new validation rule in Laravel.

Sponsored content