1、在app/Providers/AppServiceProvider.php中添加验证规则函数:
<pre>
<?php
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend('is_odd_string', function($attribute, $value, $parameters, $validator) {
if(!empty($value) && (strlen($value) % 2) == 0){
return true;
}
return false;
});
}
</pre>
2、在validation.php中添加自定义验证规则提示:
<pre>
<?php
return [
//自定义
'is_odd_string' => "The :attribute must be even string lenght.",
]
</pre>
3、在控制器中使用:
<pre>
public function store(Request $request)
{
$this->validate($request, [
'users_name' => 'required|is_odd_string',
'user_password' => 'required',
'date' => 'required|date',
], [], [
'users_name' => '用户名', //修改提示时变量的名称
'user_password' => '密码',
'date'=>'日期',
]);
return redirect('Session');
}
</pre>
4、前端显示
<pre>
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li> @endforeach
</ul> </div>
@endif
</pre>