最近在学laravel5中有一个操作是对添加表单数据做验证,如果数据不符合要求可以返回上一页对错误进行提示。
大概就是这样了。
laravel中的操作为:
![](https://i-blog.csdnimg.cn/blog_migrate/cd985e7a37c67f32e66a64750477fc5a.png)
大概就是这样了。
laravel中的操作为:
$validator=Validator::make($data,$rules,$msg);
不符合要求操作则返回上一页并连错误一起返回:
if($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
在视图中显示错误:
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
查看了withError这个方法:
/**
* Flash a container of errors to the session.
*
* @param \Illuminate\Contracts\Support\MessageProvider|array|string $provider
* @param string $key
* @return $this
*/
public function withErrors($provider, $key = 'default')
{
$value = $this->parseErrors($provider);
$this->session->flash(
'errors', $this->session->get('errors', new ViewErrorBag)->put($key, $value)
);
return $this;
}
那么原理很清楚了,在thinkphp中要做到相同的效果就很简单了,那么我们在操作失败的时候可以用这样一个简单的例子:
Session::flash('myerror',"该类型已存在");
$this->redirect('admin/index');//这里返回的是我操作的页面
在视图中:
{if(session('myerror'))}
<div class="alert alert-danger">
<ul>
<li>{$Think.session.myerror}</li>
</ul>
</div>
{/if}
得到的效果和上面laravel实现的是一样的效果。