Laravel验证复选框的某些值

时间:2016-03-08 05:35:04

标签: laravel

我只需要知道如何验证我的复选框值数组是否在某个值列表中。所以,我正在使用" in:"验证规则如下所示,但它返回了复选框的值无效的错误。我是否需要做一些不同的事情,因为它是通过AJAX发送的一系列值?

控制器:

if ($request->ajax())
{
    /*Create record in UserType Model with the values from the Type checkboxes*/

    $Type = Input::get('Type');

    $this->validate($request, [
        'Type' => 'required|in:A,B,C,D',
    ],[
        'required' => 'You must select at least one.',
    ]);

    foreach ($Type as $key => $value)
    {
        Auth::user()->userType()->create([
            'profile_id' => Auth::user()->id,
            'type' => $value,
        ]);
    }
}

在我的表格中,我有以下输入......

<input type="checkbox" name="Type[]" value="A"/>
<input type="checkbox" name="Type[]" value="B"/>
<input type="checkbox" name="Type[]" value="C"/>

更新:

因此,我在Laravel文档中发现,您可以使用*来验证数组,以获取数组中的键/值。但是,在我的数组中它只是输入[]所以我已经尝试了以下但没有运气。

$this->validate($request,[
    'type.*' => 'required|in:A,B,C,D'
    // or
    'type*' => 'required|in:A,B,C,D'
]);

只是不工作。我知道我需要使用*检索数组值。

更新:

当此验证选项仅在Laravel 5.2中可用时,我正在运行Laravel 5.1。解决。

3 个答案:

答案 0 :(得分:2)

首先:使用required时,in是必要的,因为它必须是AB或{{1 }}。这就像一个&#34; 多个&#34;已经要求了。

第二次:如docs所示,只需使用:

C

由于您的Input数组名为$this->validate($request,[ 'Type.*' => 'in:A,B,C,D' ],[ 'in' => 'You must select at least one.', ]); 。这将验证名为Type的所有输入。

要清楚,星号可以用例如' Type只验证名为one的输入:

Type[one]

或者输入名为'Type.one' => 'in:A,B,C,D'

Type[one][name]

答案 1 :(得分:0)

你试试这个

    if($this->has('Type') && is_array($this->get('Type'))){

        foreach($this->get('Type') as $key => $Type){

            $rules['Type'.$key.'] = 'required|in:A,B,C,D';
        }

答案 2 :(得分:0)

在laravel 5 ..

        $this->validate($request, [
        'Type' => 'required|array'
    ]);

为我工作的复选框