DR *_*rry 1 validation laravel-5.2
我想创建带有自定义验证错误消息的自定义验证规则.为此,我创建了一条规则:
$rule => [
'app_id' => 'isValidTag'
]
Run Code Online (Sandbox Code Playgroud)
并为自定义消息:
$message => [
app_id.isValidTag => 'Not a Valid id'
];
Run Code Online (Sandbox Code Playgroud)
之后我创建了服务提供商:
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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我的自定义验证类是:
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;
}
Run Code Online (Sandbox Code Playgroud)
一切正常,但问题是我的自定义消息app_id.isValidTag是不工作,即使所有其他消息都正常工作.
请建议我在这里或Laravel 5.2中遗漏的内容,显示消息有一些变化.任何想法将不胜感激.
这是一个很好的教程:http://itsolutionstuff.com/post/laravel-5-create-custom-validation-rule-exampleexample.html
我认为你做到了Laravel 4.*方式.这是 我在Laravel 5.2中完成的方式,在我的例子中,我正在制作注册授权表格,因此像AuthController.php这样的文件是预制的:
AuthController.php
Validator::make($data, [
...
// add your field for validation
'name_of_the_field' => 'validation_tag', // validation tag from validation.php
...
Run Code Online (Sandbox Code Playgroud)CustomAuthProvider.php //如果您没有创建自定义提供程序,请使用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;
});
Run Code Online (Sandbox Code Playgroud)validation.php
...
// add your validation tag and message to be displayed
'validation_tag' => 'The field :attribute isn't good',
...
Run Code Online (Sandbox Code Playgroud)file.blade.php //在页面末尾添加所有错误添加
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
Run Code Online (Sandbox Code Playgroud)