laravel自定义验证在ServiceProvider中定义时返回空错误 [英] laravel custom validation return empty errors when I defined it in the ServiceProvider
问题描述
当我在经过验证的服务提供者"中定义了自定义验证时.当失败时,我得到了空的MessageBox.我不明白为什么会这样.
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.
已更新:
<?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;
} );
}
}
在控制器中
private function isValid()
{
$this->validation = Validator::make( $this->attributes, [
'input' => 'custom_validation'
] );
dd($this->validation->errors()); //returned
// MessageBag{#668 #messages: [] #format: ":message" }
} }
UPDATE2: 我的app.php文件
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
第2步:在启动方法中将以下内容添加到您的服务提供商中
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;
});
}
第3步: 在提供程序部分将您提供的服务注册到config/app.php
Step 3: Register your service provide to config/app.php in provider section
App\Providers\ValidatorServiceProvider::class
第4步(Laravel方法) 创建一个请求以验证您所有的输入字段
Step 4 (Laravel way) Create a request to validate all of your input field
php artisan make:request CustomValidationRequest
第5步: 将以下内容添加到请求中
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
这篇关于laravel自定义验证在ServiceProvider中定义时返回空错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!