验证 Laravel 5 数组

5
我的ajax脚本发送的数组如下: 这个数组属于Input::get('questions')
 Array
(
    [0] => Array
        (
            [name] => fields[]
            [value] => test1
        )

    [1] => Array
        (
            [name] => fields[]
            [value] => test2
        )

)

在HTML部分,用户可以添加多个字段。
我需要像这样的东西,你能帮我吗?
           $inputs = array(
                'fields'    => Input::get('questions')
            );

            $rules = array(
                'fields'    => 'required'
            );
            $validator = Validator::make($inputs,$rules);

                if($validator -> fails()){
                    print_r($validator -> messages() ->all());
                }else{
                    return 'success';
                }
2个回答

3

简单易懂:使用 for-each 分别验证每个 question

// First, your 'question' input var is already an array, so just get it
$questions = Input::get('questions');

// Define the rules for *each* question
$rules = [
    'fields' => 'required'
];

// Iterate and validate each question
foreach ($questions as $question)
{
    $validator = Validator::make( $question, $rules );

    if ($validator->fails()) return $validator->messages()->all();
}

return 'success';

0

Laravel自定义数组元素验证

打开以下文件

/resources/lang/en/validation.php

然后添加自定义消息

'numericarray'         => 'The :attribute must be numeric array value.',
'requiredarray'        => 'The :attribute must required all element.',

因此,请打开另一个文件

/app/Providers/AppServiceProvider.php

现在使用以下代码替换引导函数的代码。

public function boot()
{
    // it is for integer type array checking.
    $this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
    {
        foreach ($value as $v) {
            if (!is_int($v)) {
                return false;
            }
        }
        return true;
    });

   // it is for integer type element required.
   $this->app['validator']->extend('requiredarray', function ($attribute, $value, $parameters)
    {
        foreach ($value as $v) {
            if(empty($v)){
                return false;
            }
        }
        return true;
    });
}

现在可以使用requiredarray来要求数组元素。同时,也可以使用numericarray来检查数组元素是否为整数类型。
$this->validate($request, [
            'arrayName1' => 'requiredarray',
            'arrayName2' => 'numericarray'
        ]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接