1

Is there a way to force an error when using Validator Class in Laravel 5.1?

For now, I've done the traditional way calling $validator = Validator::make($request->all(), $rules), which is working fine. Also, I'm attempting to make another validation (manual one) and push it into $validator, but I can't get true when I call $validator->fails().

Even using $validator->errors()->add('field','message') I couldn't force it. Is there another way?

2 Answers 2

2

In order to make validation fail, you need to define a validation rule that won't be met. Easiest way is to require some non-existent field.

This will do the trick:

$rules['some_non_existent_field'] = 'required';
$validator = Validator::make($request->all(), $rules);
dd($validator->fails());
Sign up to request clarification or add additional context in comments.

Comments

1

I had the same problem too
adding error to Validator doesn't make It to fail, so you need to make a trap for It that forces It to, maybe a required input that doesn't even exist...
but that will make a confusing error for user (example: unreal_input is required),
you'd easily change the message to explain what actually made you to fail the process...

$req = Request::all();
$rules = [/*...*/];

if(/*something's wrong*/){
    $rules['unreal_input'] = 'required'; // a confusing error in your errors list...
    $messages['unreal_input.required'] = '/* explain the real problem in here*/';
}

$validator = Validator::make($req, $rules,$messages);

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

so in the code above you've manually checked if something's wrong, then you've made a trap for Validator, then you've changed the message to what the real problem was.

NOTE: I suggest you to use a random value instead of something like unreal_input , because If you do this, the user may(?) guess the input's name, and easily using F12 he/she would pass the validation and give some invalid data to you

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.