问题
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