laravel custom validation return empty errors when I defined it in the ServiceProvider

心已入冬 提交于 2019-12-13 07:11:44

问题


When I defined a custom validation in the Validated Service Provider. And when it is failed I got empty MessageBox. I don't understand why it is happens.

UPDATED:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ValidatorServiceProvider extends ServiceProvider
{

    public function boot()
    {
        \Validator::extend('custom_validation', function ( $attribute, $value, $parameters ) {
            return false;
        } );
    }
}

in the controller

private function isValid()
{
    $this->validation = Validator::make( $this->attributes, [
       'input' => 'custom_validation'
    ] );

    dd($this->validation->errors()); //returned 
    // MessageBag{#668 #messages: [] #format: ":message" }

} }

UPDATE2: my app.php file

'providers' => [
...
    App\Providers\ValidatorServiceProvider::class,
],

回答1:


To create a Custom Validator: Step 1:

-> Create a Service provide php aritsan make:proider ValidatorServiceProvider

Step 2: add the following to your service provider in boot method

public function boot()
{
    Validator::extend('custom_validation', function($attribute, $value, $parameters, $validator) {

        //checks if input value is 1
       if($value = 1) return true;

        return false;
    });
}

Step 3: Register your service provide to config/app.php in provider section

    App\Providers\ValidatorServiceProvider::class

Step 4 (Laravel way) Create a request to validate all of your input field

php artisan make:request CustomValidationRequest

Step 5: Add the following to the request

//validation rules
public function rules()
{
    return [
        'digit'  =>  'required|custom_validation'
    ];
}

//message
public function messages()
{
    return [
        'digit.required'    =>  'This value is required.',
        'digit.custom_validation'  =>  'This custom validation is required'
    ];
}

Now use it in you controller

public function store(Request CustomValidationRequest)
{
  //validation will be done and send back to view if error occurred
}

Hopefully this will help Cheers




回答2:


Are you using the laravel Validator facade ? if so you do not need to define it from the service provider?



来源:https://stackoverflow.com/questions/40286037/laravel-custom-validation-return-empty-errors-when-i-defined-it-in-the-servicepr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!