laravel的validator验证
生活随笔
收集整理的這篇文章主要介紹了
laravel的validator验证
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.引入對(duì)應(yīng)的類
use Illuminate\Support\Facades\Validator;2.自定義規(guī)則,寫在模型,控制器,中間件都可以
$rules = ['password' => 'required|between;6,20|confirmed', 'name' => 'required|between;3,8', ];3.自定義提示,laravel自帶的提示是英文的這里修改為中文
$message = ['password.required' => '密碼不能為空','password.between' => '密碼6到20位','password.confirmed' => '密碼與確認(rèn)密碼不一致'];4.驗(yàn)證
//$input 為獲取到的需要驗(yàn)證的數(shù)組$validator = Validator::make($input,$rules,$message); if($validator->passes){return true;} else {return false;}5.特殊驗(yàn)證
驗(yàn)證兩個(gè)字段不一致 可使用??confirmed,在需要驗(yàn)證的值后面加??confirmation 例:
<input type="password" placeholder="密碼" id="password" name="password"> <input type="password" placeholder="確認(rèn)新密碼" id="password2" name="password_confirmation">也可直接在數(shù)組中修改健名。
6.錯(cuò)誤信息
if($validator->fails()){//驗(yàn)證字段失敗,失敗信息自己封裝處理$validator->errors()->first(); //返回第一個(gè)錯(cuò)誤消息,一般用這個(gè)就行了//$validator->errors()->all(); //返回全部錯(cuò)誤消息,不帶表單下標(biāo)//$validator->errors(); //返回全部錯(cuò)誤消息,帶表單下標(biāo)}return back()->withErrors($vilidator);
others:
//驗(yàn)證規(guī)則protected $role = ['passwordOld' => 'required|min:6|max:12', 'passwordNew' => 'required|min:6|max:12|confirmed','passwordNew_confirmation' => 'required|min:6|max:12',]; //這三個(gè)字段為提交表單的input//提示信息 attribute是占位符,這里是custom方法的valueprotected $msgs = ['required' => ':attribute不能為空','min' => ':attribute最少:min字符','max' => ':attribute最長(zhǎng):max字符''confirmed' => ':attribute輸入不一致'];// 自定義字段名稱,提示的時(shí)候用到protected $custom = ['passwordOld' => '原密碼','passwordNew' => '新密碼','passwordNew_confirmation' => '密碼確認(rèn)',];//設(shè)置密碼 $input提交過(guò)來(lái)的表單和數(shù)據(jù)public function setPassword($input){$validator = \Validator::make($input,$this->role,$this->msgs,$this->custom);if($validator->fails()){//驗(yàn)證字段失敗,失敗信息自己封裝處理$validator->errors()->first(); //返回第一個(gè)錯(cuò)誤消息,一般用這個(gè)就行了//$validator->errors()->all(); //返回全部錯(cuò)誤消息,不帶表單下標(biāo)//$validator->errors(); //返回全部錯(cuò)誤消息,帶表單下標(biāo)}}轉(zhuǎn)載自??http://blog.daozys.com/goods_100.html
?
轉(zhuǎn)載于:https://www.cnblogs.com/zyjfire/p/10566021.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的laravel的validator验证的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: IPSec协议;IPv6为何增加对IPS
- 下一篇: 2:word定制工作界面