Laravel 验证错误视图
Laravel validation error view
我在 Laravel 的一个页面上有两种不同的表单。
这是注册页面,同时具有注册和登录表单。当我在注册表单上遇到错误时,登录表单也会出现同样的错误(见图)。解决此问题的最佳方法是什么?
我直接在我的表单下使用 @include('errors.common')
来显示验证错误。
当控制器验证失败时,您必须在重定向中指出是登录还是注册失败:
return redirect()->back()->withInput()->with('loginFail', true);
现在,在您拥有登录和注册表单的视图中,相应地加载 @include('errors.common')
:
@if(Session::has('loginFail')
@include('errors.common')
@endif
注册表使用相同的原则。
另一种解决方案,如果您使用 Laravel
随附的 AuthController.php
。
在注册表单中添加一个隐藏字段,名称为register
,值为1
。
在登录表单中添加一个名为login
、值为1
的隐藏字段。
现在您可以像这样控制何时显示错误:
// Registration
@if(!$errors->isEmpty())
@if(!empty(old('register')))
@include('errors.common')
@endif
@endif
// Login
@if(!$errors->isEmpty())
@if(!empty(old('login)))
@include('errors.common')
@endif
@endif
https://laravel.com/docs/5.0/validation#error-messages-and-views
Named Error Bags
If you have multiple forms on a single page, you may wish to name the MessageBag of errors. This will allow you to retrieve the error messages for a specific form. Simply pass a name as the second argument to withErrors:
return redirect('register')->withErrors($validator, 'login');
You may then access the named MessageBag instance from the $errors variable:
<?php echo $errors->login->first('email'); ?>
我在 Laravel 的一个页面上有两种不同的表单。 这是注册页面,同时具有注册和登录表单。当我在注册表单上遇到错误时,登录表单也会出现同样的错误(见图)。解决此问题的最佳方法是什么?
我直接在我的表单下使用 @include('errors.common')
来显示验证错误。
当控制器验证失败时,您必须在重定向中指出是登录还是注册失败:
return redirect()->back()->withInput()->with('loginFail', true);
现在,在您拥有登录和注册表单的视图中,相应地加载 @include('errors.common')
:
@if(Session::has('loginFail')
@include('errors.common')
@endif
注册表使用相同的原则。
另一种解决方案,如果您使用 Laravel
随附的 AuthController.php
。
在注册表单中添加一个隐藏字段,名称为register
,值为1
。
在登录表单中添加一个名为login
、值为1
的隐藏字段。
现在您可以像这样控制何时显示错误:
// Registration
@if(!$errors->isEmpty())
@if(!empty(old('register')))
@include('errors.common')
@endif
@endif
// Login
@if(!$errors->isEmpty())
@if(!empty(old('login)))
@include('errors.common')
@endif
@endif
https://laravel.com/docs/5.0/validation#error-messages-and-views
Named Error Bags
If you have multiple forms on a single page, you may wish to name the MessageBag of errors. This will allow you to retrieve the error messages for a specific form. Simply pass a name as the second argument to withErrors:
return redirect('register')->withErrors($validator, 'login');
You may then access the named MessageBag instance from the $errors variable:
<?php echo $errors->login->first('email'); ?>