1、在Model中定义验证规则
如Article
public static $rules = [
'title' => 'required',
'category_id' => 'required',
'content' => 'required',
];
2、在Controller中使用验证
$validator = Validator::make($request->all(), Article::$rules);
if ($validator->fails()) {
return redirect($redirect)
->withErrors($validator)
->withInput();
}
3、添加验证错误提示
把resources/lang/en下的validation.phpfu复制到zh-CN文件夹下
把里面不需要的信息都清理掉
根据说明
在语言文件中指定自定义消息
在很多案例中,你可能想要在语言文件中指定自定义消息而不是将它们直接传递给 Validator
。要实现这个,添加消息到 resources/lang/xx/validation.php
语言文件的 custom
数组:
'custom' => [
'email' => [
'required' => '邮箱地址不能为空!',
],
],
在语言文件中指定自定义属性
如果你想要将验证消息的 :attribute
部分替换成自定义属性名称,可以在语言文件 resources/lang/xx/validation.php
的 attributes
数组中指定自定义名称:
'attributes' => [
'email' => '邮箱地址',
],
我们只需要保留custom和attributes即可
添加验证错误提示
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'title' => [
'required' => '标题不能为空!'
],
'category_id' => [
'required' => '分类不能为空!'
],
'content' => [
'required' => '内容不能为空!'
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [
'title' => '标题',
'category_id' => '分类',
'content' => '内容',
],
4、使用验证
public function error_html($key, $errors) {
$html = '';
if(!empty($errors)) {
if($errors->has($key)) {
$html .= '<label class="control-label error-label">';
foreach ($errors->get($key) as $message) {
$html .= $message .' ';
}
$html .= '</label>';
}
}
return $html;
}