Laravel 5.2数组验证 [英] Laravel 5.2 array validation
问题描述
我有一个输入字段,我正在使用jQuery动态添加该字段,它是视频链接的输入字段,用户可以随意添加任意多次,并且我需要检查url是否对所有用户有效如果在字段中写了一些东西,我还需要将其保留为可选字段.我试图通过遵循此示例来做到这一点,但是显然对我不起作用:
I have an input field that I am adding dynamically with jQuery, it is the input field for video links, that a user can add as many times as he wants to, and I need to check if the url is valid for all the fields if something is written in them, I also need to leave it as an optional field. I was trying to do it by following this example but that is obviously not working for me:
这是我的表单字段:
{!! Form::text('external_media[]', null,['class' => 'form-control col-lg-10 external-media-input']) !!}
在我的控制器存储功能中,我试图像这样验证它:
And in my controller store function I was trying to validate it like this:
$this->validate($request->all(), [
'external_media.*' => 'present|active_url',
]);
当我从创建表单发送数据时,$request->all()
看起来像这样:
When I am sending data from the create form, $request->all()
looks like this:
array:11 [▼
"_token" => "JQXZjFEs3ETgVqh2izcmJx1h3sGryFvDkzGGtVAd"
"external_media" => array:3 [▶]
"category" => "1"
"type" => "0"
"title" => "sdbvsdb"
]
但是我得到了错误:
FatalThrowableError in ValidatesRequests.php line 49:
Type error: Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given, called in /home/vagrant/Projects/myProject/app/Http/Controllers/Admin/Articles/ArticlesController.php on line 66
我还尝试过使用请求文件中的规则进行验证:
I have also tried with making the validation with rules in a requests file like this:
$rules = [
'title' => 'required',
'text' => 'required',
//'image' => 'required|image|max:20000',
];
foreach($this->request->get('external_media') as $val)
{
$rules[$val] = 'present|active_url';
}
return $rules;
但是当我在external_media的字段为空时,出现此错误:
But then when I have a blank field for external_media, I get this error:
ErrorException in helpers.php line 531:
htmlentities() expects parameter 1 to be string, array given (View: /home/vagrant/Projects/iCoop5.2/resources/views/admin/articles/create.blade.php)
推荐答案
$inputs = request()->all();
$validator = Validator::make($inputs, [
'external_link.*' => 'required|active_url',
]);
dd($validator->messages());
别忘了在文件中添加use Validator;
.
这篇关于Laravel 5.2数组验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!