我正在创建一个网站,该网站在注册过程中允许用户上传一些图像。图像上传器是通过ajax完成的,会话中存储的数据准备好在成功注册后永久存储在数据库中。我将如何实现自定义验证规则来检查会话数据是可以的,因为它实际上并没有绑定到特定的表单字段。
目前它是这样工作的:
<?php namespace App\Services;
use App\User;
use Event;
use Validator;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
use App\Events\UserRegistered;
use Session;
class Registrar extends Validator implements RegistrarContract {
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
Validator::extend('required_images', function($attribute, $value, $parameters)
{
if (!Session::has('images') || empty(Session::get('images'))) {
return false;
} else {
return true;
}
});
return Validator::make($data, [
'first_name' => 'required_images|required|max:255',
'last_name' => 'required|max:255',
'discount_code' => 'max:255',
'register_email' => 'required|email|confirmed|max:255|unique:users,email',
'register_password' => 'required|confirmed|min:6|max:60'
]);
}
如您所见,我现在已经创建了规则所需的图像并将其绑定到first_name字段。但这与名字字段或任何其他字段无关,那么我应该怎么称呼它呢?
如果您的自定义规则不适用于验证表单数据,则不要为此制定规则。而是使用一些很酷的功能创建一个帮助器类:
namespace Services;
class Helper{
static function validateImages(){
if (!Session::has('images') || empty(Session::get('images'))) {
return false;
} else {
return true;
}
}
}
由于您的验证未附加到任何字段,因此请在视图中创建自定义警告:
@if (Session::has('warning'))
<p>{{ Session::get('warning') }}</p>
@endif
... here the form elements ...
然后,您可以通过以下方式验证数据:
if (! Helper::validateImages()){
return redirect()->back()->with("warning", "You don't have any images");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句