0

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.

Bulat
  • 6,869
  • 1
  • 29
  • 52
Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173

2 Answers2

1

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
Top-Master
  • 7,611
  • 5
  • 39
  • 71
manix
  • 14,537
  • 11
  • 70
  • 107
1

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.');
 }
]
Jee Mok
  • 6,157
  • 8
  • 47
  • 80