验证数组Laravel 5 [英] Validate array Laravel 5

查看:75
本文介绍了验证数组Laravel 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ajax脚本发送数组如下: 该数组属于Input::get('questions')

My ajax script send array like this: This array belong to Input::get('questions')

 Array
(
    [0] => Array
        (
            [name] => fields[]
            [value] => test1
        )

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

)

在html部分中,用户可以添加多个fields.

In html part user can add multiple fields.

您能帮我吗,我需要这样的东西:

Could you help me with I need something like this:

           $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';
                }

推荐答案

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

Simple: validate each question separately using a for-each:

// 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';

这篇关于验证数组Laravel 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆