Real Dreams
Real Dreams

Reputation: 18010

How to use a closure as a validator?

Is it possible to do something similar to the following in Laravel:

public function rules()
{
    return [
        'sid' => function ($input) {
            // some custom validation logic.
        }
    ];
}

public function messages()
{
    return [
        'sid' => "Invalid SID!",
    ];
}

I want to do some simple single-use validation. Creating a custom validation is an overkill.

Upvotes: 0

Views: 2396

Answers (2)

manix
manix

Reputation: 14747

There are two options here, at least.

  1. Create a custom rule via AppServiceProvider at boot() method:

     Validator::extend('my_rule', function($attribute, $value, $parameters) {
         // some custom validation logic in order to return true or false
         return $value == 'my-valid-value';
     });
    

then, you apply the rule like:

    return [
        'sid' => ['my_rule'],
    ];
  1. Or extending ValidatorServiceProvider class. Use this thread explained step by step: Custom validator in Laravel 5

Upvotes: 1

Fabio de Oliveira
Fabio de Oliveira

Reputation: 11

If you are using Laravel 5.6 or later, you may use closures.

To have $input available in the scope of the closure, you may use use keyword.

'sid' => [ function($attribute, $value, $fail) use $input {
   // your logic here
   //if that fails, so
    return $fail($attribute.' is invalid.');
 }
]

Upvotes: 1

Related Questions