Taylor's Designs
Taylor's Designs

Reputation: 57

How do I check for a specific error in Laravel 5.2 validation?

Right now, I can check for a field having a validation error in blade by using:

@if($errors->has('field_name'))
 <div class="help-block">
  Lorem Ipsum
 </div>
@endif

In my controller, I am using the not_in rule:

"field_name" => "required|string|not_in:

I want to know, can I change the if statement to check only for the not_in rule?

Example:

@if($errors->has('field_name.not_in'))

Upvotes: 3

Views: 1395

Answers (2)

jakehallas
jakehallas

Reputation: 2506

You can do this by using Laravel's custom error message.

$messages = [
    'field.required' => 'required',
    'field.string' => 'string',
    'field.not_in' => 'not_in',
];

Then by doing the following;

if($errors->has('field')){
    foreach($errors->get('field') as $error) {
        if($error == "not_in") {
            // do something
        }
    }
}

It is a very messy solution, but I cannot seem to find anything that Laravel provides for a prettier solution. I guess the question is why do you want to do this? There may be a way to provide a more elegant solution rather than working with an error bag.

Upvotes: 0

Morteza Negahi
Morteza Negahi

Reputation: 3483

@if($errors->has('field_name') and $errors->first('field_name') == 'The selected field_name is invalid.')
    this is just for not in validation for special input.
@endif

Upvotes: 1

Related Questions