Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom Dynamic Validation Rules for Laravel 5.5+

This gist will help understand custom (artisan make:rule MyRule) dynamic (rules that require more context than just the attribute and value) validation rules for Laravel 5.5+.

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class StringIsLengthRule implements Rule
{
protected $length;
protected $message = 'The string must be greater than the length';
public function __construct($length)
{
$this->length = $length;
}
public function passes($attribute, $value)
{
if (!$this->length || $this->length <= 0) {
$this->message = 'The length has to be greater than zero to validate the string';
return false;
}
return strlen($value) > $this->length;
}
public function message()
{
return $this->message;
}
}
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StringTesterRequest;
class StringTesterController extends Controller
{
public function form()
{
/**
* Assume the form is:
* <form method="POST" action="/string-tester">
* {{ csrf_field() }}
* Length: <input name="length"><br>
* String: <input name="string"><br>
* <button>Submit</button>
* </form>
*/
return view('form');
}
public function process(StringTesterRequest $request)
{
// reshow form, the form also has dump($request) in it for demonstration
return view('form', compact('request'));
}
}
<?php
namespace App\Http\Requests;
use App\Rules\StringIsLengthRule;
use Illuminate\Foundation\Http\FormRequest;
class StringTesterRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'length' => 'required|numeric',
'string' => [
'required',
new StringIsLengthRule($this->request->get('length'))
],
];
return $rules;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.