学习laravel框架有一段时间了,觉得它自带的表单验证特别好用,和大家分享分享
对于一些验证规则手册上都有,相信大家看了就会,我简单的说下怎么使用自定义正则验证:
验证手机号:'tel' => array('regex:/^1(3|4|5|7|8)\d{9}$/'), 直接加入到validate里验证即可
还有一点就是在验证时,验证出错后怎么保持原来输入的信息,下面贴上代码,更容易理解:
1、控制器
//验证表单
public function postCheck(Request $req)
{
$this->validate($req,
[
'email' => 'bail|required|email|max:25|unique:user,email',
'pwd_confirmation' => 'required|alpha_dash|between:6,20',
'pwd'=>'required|confirmed',
'explain'=>'required',
'checkbox'=>'accepted',
],
[ 'email.required' =>'We need to know your e-mail address!', //自定义错误信息
'email.email' => 'Please fill in the correct email address.!',
'email.max' => 'Mailbox length maximum 25 characters!',
'email.unique' => 'The mailbox is too fire, has been registered!', 'pwd_confirmation.required' =>'Please enter your password!',
'pwd_confirmation.between' => 'Password must be 6 to 20 characters!', 'pwd.required' => 'Please Confirm your password!',
'pwd.confirmed' => 'Confirm password error!', 'explain.required' => 'Please fill in the details!', 'checkbox.accepted' => 'Please agree to the registration agreement!', ]);
//验证通过后数据入库 $date = $req->all(); //接到的参数
$res = $this->add($date);
}
2、视图(只写了一个,其他的复制)
<div class="form-group">
<input type="email" class="form-control" placeholder="请输入邮箱" required="" id="email" name="email" value="{{old('email')}}">
</div>
//错误信息显示
@if($errors->has('email'))
<div class="alert alert-danger">
@foreach($errors->get('email') as $error)
{{$error}}
@endforeach
</div>
@endif