DR Jerry
DR Jerry

Reputation: 71

Laravel 5.2 Custom validation message with custom validation function

I want to create custom validation rule with custom validation error message. For this I created a rule:

$rule => [
    'app_id' => 'isValidTag'
]

And for custom message:

$message => [
   app_id.isValidTag   => 'Not a Valid id'
];

After that I created Service Provider:

class CustomValidationServiceProvider extends ServiceProvider
{
    public function boot() {

    //parent::boot();

    $this->app->validator->resolver(function($transator,$data,$rules,$messages){
            return new CustomValidator($transator,$data,$rules,$messages);
        });
    }
}

And my Custom validation class is:

class CustomValidator extends Validator {
    if(empty($parameters)) {
        return true;
    }

    $conext = $parameters[0];
    $tag = Tag::where('id', $value)->where('context', $conext)->get();

    $flag = false;
    if($tag->count() > 0) {
        $flag = true;
    }       

    return $flag;
}

All is working fine but the issue is my custom message for app_id.isValidTag is not working even all other message are working fine.

Please suggest me what I missing here or in Laravel 5.2 there is some change to display message. Any idea will be appreciated.

Upvotes: 1

Views: 4737

Answers (1)

user3632055
user3632055

Reputation: 236

Here is a great tutorial for this: http://itsolutionstuff.com/post/laravel-5-create-custom-validation-rule-exampleexample.html

I think you did it Laravel 4.* way. This is how it is done in Laravel 5.2 in my example where i was making registration authorisation form so files like AuthController.php was premade:

  1. AuthController.php

    Validator::make($data, [
        ...
        // add your field for validation
        'name_of_the_field' => 'validation_tag', // validation tag from validation.php
        ...
    
  2. CustomAuthProvider.php // if you didn't make a custom provider use Providers/AppServiceProvider.php

    public function boot() {
        ...
        Validator::extend('validation_tag', function($attribute, $value, $parameters, $validator) {
                // handle here your validation
                if (  your_query ) {
                    return true;
                }
                return false;
        });
    
  3. validation.php

    ...
    // add your validation tag and message to be displayed
    'validation_tag'           => 'The field :attribute isn't good',
    ...
    
  4. file.blade.php // to add at the end of the page all your errors add

    @if (count($errors) > 0)
          <div class="alert alert-danger">
                 <ul>
                       @foreach ($errors->all() as $error)
                             <li>{{ $error }}</li>
                       @endforeach
                 </ul>
           </div>
    @endif
    

Upvotes: 5

Related Questions