laravel5表单验证详解编程语言

学习laravel框架有一段时间了,觉得它自带的表单验证特别好用,和大家分享分享

对于一些验证规则手册上都有,相信大家看了就会,我简单的说下怎么使用自定义正则验证:

验证手机号:‘tel’ => array(‘regex:/^1(3|4|5|7|8)/d{9}$/’),  直接加入到validate里验证即可

 

还有一点就是在验证时,验证出错后怎么保持原来输入的信息,下面贴上代码,更容易理解:

1、控制器

 1 //验证表单 
 2     public function postCheck(Request $req) 
 3     {     
 4        
 5         $this->validate($req,  
 6          [ 
 7             'email' => 'bail|required|email|max:25|unique:user,email', 
 8             'pwd_confirmation' => 'required|alpha_dash|between:6,20', 
 9             'pwd'=>'required|confirmed', 
10             'explain'=>'required', 
11             'checkbox'=>'accepted', 
12         ], 
13         [    'email.required' =>'We need to know your e-mail address!',   //自定义错误信息 
14             'email.email' => 'Please fill in the correct email address.!', 
15             'email.max' => 'Mailbox length maximum 25 characters!', 
16             'email.unique' => 'The mailbox is too fire, has been registered!', 
17  
18             'pwd_confirmation.required' =>'Please enter your password!', 
19             'pwd_confirmation.between' => 'Password must be 6 to 20 characters!', 
20  
21             'pwd.required' => 'Please Confirm your password!', 
22             'pwd.confirmed' => 'Confirm password error!', 
23  
24             'explain.required' => 'Please fill in the details!', 
25              
26             'checkbox.accepted' => 'Please agree to the registration agreement!', 
27  
28         ]); 
29               //验证通过后数据入库 
30      
31         $date = $req->all();  //接到的参数 
32         $res = $this->add($date); 
33 } 
34     

2、视图(只写了一个,其他的复制)

 1                 <div class="form-group"> 
 2                     <input type="email" class="form-control" placeholder="请输入邮箱" required="" id="email" name="email" value="{{old('email')}}"> 
 3                 </div>
          //错误信息显示 4 @if($errors->has('email')) 5 <div class="alert alert-danger"> 6 @foreach($errors->get('email') as $error) 7 {{$error}} 8 @endforeach 9 </div> 10 @endif

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/16014.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论