mpen
mpen

Reputation: 283335

How to add a custom validation error?

Here's what I've got:

$data = Input::all();
$validator = Validator::make($data, Vehicle::$rules);

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

But my Vehicle::$rules can't cover all the things I need to validate. How can I add additional error messages into $validator?

I've tried

$validator->errors()->add("xxx","yyy")

But it doesn't seem to actually add an error.

Upvotes: 0

Views: 68

Answers (2)

Pawel Bieszczad
Pawel Bieszczad

Reputation: 13335

So if I understand correctly you want to run additional checks on the date and if it has an error add it to the withErrors() method. Here's what I think you are looking for:

$errors = [];
$data = Input::all();
$validator = Validator::make($data, Vehicle::$rules);

if($validator->fails()) {
    $errors = $validator->errors()->toArray();
}

// "manual" check
if($data['field'] < 10){
    $errors['field'] = ['My custom error.']
}

if(!empty($errors)){     
    return Redirect::back()->withErrors($errors)->withInput();
}

Upvotes: 1

smartrahat
smartrahat

Reputation: 5659

If you want to change default validation messages you can do it by editing this file resources\lang\en\validation.php

If you want to check the data requested from a form is fit for you application or not you can use if condition. Example: If you want to make username field mandatory (required in Laravel validation) your code should look like this in controller-

public function store(Request $request){
    if($request['username'] == ''){
        Session::flash('error_message','The username field is required!');
        return redirect('previousPageRoute');
    }

    Session::flash('success_message','Username collected successfully!');
    return redirect('nextPageRoute');
}

And your view file should have this to show session messages-

@if(Session::has('error_message'))
    {{ Session::get('error_message') }}
@if(Session::has('success_message'))
    {{ Session::get('success_message') }}
@endif

Upvotes: 0

Related Questions