Laravel验证之间不将逗号分隔的字符串转换为数组?

时间:2015-12-01 06:35:37

标签: php validation laravel laravel-5

只是尝试做一些标签验证。首先检查标签数量(以逗号分隔的id列表)。

class SomePostRequest extends Request
{
    public function rules()
    {
        return [
            'tags' => 'between:2,5'
        ];
    }


    public function all()
    {
        $input = parent::all();

        $input['tags'] = explode(',', @$input['tags']);

        return $input;
    }

}

它不断地将消息吐出

The tags must be between 2 and 5 characters.

而不是正确的数组消息:

The :attribute must have between :min and :max items.

1 个答案:

答案 0 :(得分:0)

尝试为您的要求使用自定义验证规则:

$this->app['validator']->extend('tag', function ($attribute, $value, $parameters)
{
    $tags = explode(',', $value);
    if(count($tags) >= 2 || count($tags) <= 5)){
        return false;
    }
});

然后规则将是

public function rules(){
    return [
        'tags' => ['tag']
    ];
}

并且消息可以通过

更新
public function messages() {
        return [
            'tags.tag' => 'The :attribute must have between :min and :max items.'];

}

我希望,你有基本的想法来实现这个要求,让我知道它是否有帮助。