PHP框架Laravel中有很多种验证参数的方式,本文分享两种一点PHP博主比较常用的方法。第一种通过Validator验证类进行验证,第二种使用form request 表单验证类方式进行验证。
有不明确的或者好的提议可以在下方给一点博主留言。
一.使用Validator验证类。
1.首先引入该类。
1 |
use Validator; |
2.使用该类中的make方法进行验证。
1 |
$validator = Validator::make($input, $rules, $messages);//最后一个参数可以不写,用来自定义第二个参数中的验证规则报错信息 |
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
$messages = [ 'required' => '不能为空', 'url' => '格式错误', 'numeric' => '格式错误', 'email' => '格式错误', 'string' => '格式错误', ]; $validator = Validator::make($request->except('_token'), [ 'stitle' => 'required|string', 'surl' => 'required|url', 'skeywords' => 'required|string', 'skeywords' => 'required|string', 'sdescription' => 'required|string', 's_name' => 'required|string', 's_phone' => 'required|numeric', 's_qq' => 'required|numeric', 's_email' => 'required|email', 'scopyright' => 'required|string', ],$messages); |
3.验证是否通过验证以及返回错误信息。
1 2 3 4 5 6 7 8 9 |
if ($validator->fails()) { return redirect('admin/info') ->withErrors($validator) ->withInput($data); } |
注:使用withErrors($validator),注入错误信息,view层使用errors()->first('需要获得哪个字段的报错信息'),使用之前可以用errors->has('字段')判断是否有错误。还可以使用errors->any()判断验证是否有错,errors->all(),获得所有报错信息可以遍历出来。使用withInput($data)可以把数据带回上一个view层,view层使用old('下标')取值。一般用做验证失败后,把用户传递的数据,带回去,提高用户体验。
二、laravel 自定义 form request 表单验证类
//出现在app/http/requests中
1.使用命令行
1 |
php artisan make:request StoreCommentRequest |
2.authorize()方法中改成true,这是做权限认证的,在这里可以操作数据库等,如果条件满足就返回 true,否则返回false不允许访问该方法。
3.rules()方式在里面定义你的路由规则。
4.message()在里面定义你的自定义报错提示信息。
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
class postConfigInfoRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ publicfunctionauthorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ publicfunctionrules() { return [ //规则 'sname'=>'required|string', 'stitle'=>'required|string', 'surl'=>'required|url', 'skeywords'=>'required|string', 'skeywords'=>'required|string', 'sdescription'=>'required|string', 's_name'=>'required|string', 's_phone'=>'required|numeric', 's_qq'=>'required|numeric', 's_email'=>'required|email', 'scopyright'=>'required|string', ]; } publicfunctionmessages() { return [ 'required'=>'不能为空', 'url'=>'格式错误', 'numeric'=>'格式错误', 'email'=>'格式错误', 'string'=>'格式错误', ]; } } |
4.在需要使用的类中将其引入
1 |
use App\Http\Requests\admin\postConfigInfoRequest; |
1 |
public function postInfo(postConfigInfoRequest $request){} //引用后这样既可 |
有小伙伴想要看在laravel框架中如何自定义封装函数或者类的可以看这篇文章。
浙江一点PHP,每天一点技术分享。