Search code examples
phplaravelvalidationlaravel-5laravel-validation

attaching an error to validator in laravel 5


I'm using Validator Facade , here's the code

$req = Request::all();
$rules = [
    'name'=>'required|min:3|max:20'
];
$validator = Validator::make($req, $rules);

if(/*another problem*/){
    // ??
}      

if ($validator->fails()) {
    return redirect()->back()->withErrors($validator)->withInput();
}

I want to keep the errors that the Laravel's Validator make's It self and attach some others to them (If needed). So for example If there was nothing wrong with the name input but my if statement found an error, the Validator would fail.


Solution

  • Validator MessageBag

    You can add the message to the name property of your form by adding it to the Validator MessageBag.

    if(/*another problem*/) {
        $validator->getMessageBag()->add('name', 'Something else does not check out!');
    
        return redirect()->back()->withErrors($validator)->withInput();
    }
    

    I would recommend doing this logic after you check if the formvalidation has failed, because just adding the message to the MessageBag will not set your validation as failed. Then you can manually return the redirect after one or more of these checks have been done to redirect to the form with errors and input.