How do I validate if array is empty?

2019-08-13 04:55发布

问题:

I have a form with 5 multiple-choice dropdown lists. When submitted, I am trying to run some validation to check that at least one item has been checked.

The code in my controller;

$input = Request::except('postcode_id'); //all user input from the form

$validator = \Validator::make(
    [
        $input => 'required'
    ]
);

if ($validator->fails())
{
    print "failed";
}else{
    print "passed";
}

The error I get is; Illegal offset type. I think I might need to do a custom validator but would like to check first in case there is an easier way.

回答1:

The first argument of Validator::make() is the data, and the second is an array of validation rules, which are indexed by the input names. You can use required_without_all to validate that at least one must be present, but it is a little verbose:

$validator = \Validator::make($input, [
    'dropdown_1' => 'required_without_all:dropdown_2,dropdown_3,dropdown_4,dropdown_5'
    'dropdown_2' => 'required_without_all:dropdown_1,dropdown_3,dropdown_4,dropdown_5'
    'dropdown_3' => 'required_without_all:dropdown_1,dropdown_2,dropdown_4,dropdown_5'
    'dropdown_4' => 'required_without_all:dropdown_1,dropdown_2,dropdown_4,dropdown_5'
    'dropdown_5' => 'required_without_all:dropdown_1,dropdown_2,dropdown_3,dropdown_4'
]);

Or write some code to generate the $rules array:

$fields = ['dropdown_1', 'dropdown_2', 'dropdown_3', 'dropdown_4', 'dropdown_5'];
$rules = [];
foreach ($fields as $i => $field) {
    $rules[$field] = 'required_without_all:' . implode(',', array_except($fields, $i));
}
$validator = \Validator::make($input, $rules);


回答2:

You need to use strings in your validator, not variables. Try this instead.

$validator = \Validator::make(
    [
        'input' => 'required'
    ]
);

Custom validator itself is not too difficult. I am using it all the time for array input validation. In Laravel 5 Request I will do something like that

public function __construct() {
    Validator::extend("pcc", function($attribute, $value, $parameters) {
        $rules = [
            'container_id' => 'exists:containers,id'
        ];
        foreach ($value as $containerId) {
                $data = [
                    'container_id' => $containerId
                ];
                $validator = Validator::make($data, $rules);
                if ($validator->fails()) {
                    return false;
                }
            }
        return true;
    });
}

public function rules() {
    return [
        'containers' => 'required|pcc',
    ];
}