- [第一种:validator门面验证 ]
直接使用Validator类来验证,Validator::make()方法 第一个参数为表单提交的参数,第二个为校验规则,第三个为自定义提示消息,第四个为自定义名称(为 :attribute 占位符提供准确的名称)
public function doSubmit(Request $request) {
$validator=Validator::make($request->input(),[
'title' => 'required|min:3|max:12',
'url' => 'required|url',
'code' => 'required|captcha',
],[
'required'=> ':attribute为必填项',
'min' => ':attribute至少:min个字符',
'max' => ':attribute最多:max个字符',
'url' => '链接地址格式错误',
'captcha' => '验证码错误',
],[
'title' => '网站名称',
'url' => '链接地址',
'code' => '验证码',
]);
if ($validator->fails()) {
return redirect(pagename) //写上对应路径
->withErrors($validator)
->withInput();
} else {
dosubmit...
}
}
- [ 第二种:创建Validator表单请求【推荐】]
php artisan make:request YourRequestName
使用artisan命令在app\Http\Requests文件夹下创建了一个YourRequestName.php的文件
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class YourRequestName extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true; //注:这里改成true!此处用于控制访问权限,若要区分权限可以在这里添加
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|min:3|max:12',
'url' => 'required|url',
'code' => 'required|captcha',
];
}
//验证器错误的自定义消息
public function messages()
{
return [
'required' => ':attribute为必填项',
'min' => ':attribute至少:min个字符',
'max' => ':attribute最多:max个字符',
'url' => ':attribute格式错误',
'code' => ':attribute错误',
];
}
//自定义字段名称
function attributes()
{
return [
'title' => '名称',
'url' => '网址',
'code' => '验证码',
];
}
}
控制器中直接用use的方式引用上述文件
use App\Http\Requests\YourRequestName;
public function doSubmit(YourRequestName $request) {
dosubmit...
}
视图渲染提示信息
@if ($errors->any())
<div class="alert alert-danger" style='color:red;font-size:12px;'>
@foreach ($errors->all() as $error)
<span>[{{ $error }}]</span>
@endforeach
</div>
@endif