Laravel验证 - 逗号分隔字符串输入为数组

时间:2022-01-11 00:17:45

How can I validate one input with multiple values? I'm using bootstrap tagsinput plugin. It returns all tags in one field. I need to validate this tags - unique. First I'm trying to place this tags into array and then validate it in request but still no luck. Here is my code in request:

如何验证具有多个值的一个输入?我正在使用bootstrap tagsinput插件。它返回一个字段中的所有标记。我需要验证这个标签 - 独一无二。首先,我正在尝试将此标记放入数组中,然后在请求中验证它,但仍然没有运气。这是我的请求中的代码:

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

    // checkbox status
    if(array_key_exists('keywords', $postData)) {

        // put keywords into array
        $keywords = explode(',', $postData['keywords']);

        $test = [];
        $i = 0;
        foreach($keywords as $keyword)
        {
            $test[$i] = $keyword;
            $i++;
        }
        $postData['keywords'] = $test;

    }

    return $postData;

}

public function rules()
{
    $rules = [
        'title' => 'required|min:3|unique:subdomain_categories,title|unique:subdomain_keywords,keyword',
        'description' => '',
        'image' => 'required|image',
        'keywords.*' => 'min:3'
    ];

    return $rules;
}

But as soon as keyword becomes invalid I get this error:

但是一旦关键字变为无效,我就会收到此错误:

ErrorException in helpers.php line 531: htmlentities() expects parameter 1 to be string, array given.

helpers.php第531行中的ErrorException:htmlentities()期望参数1为字符串,给定数组。

Any ideas what's wrong?

有什么想法有什么不对吗?

2 个解决方案

#1


2  

I was running into a similar problem with comma separated emails on 5.4. Here's how I solved it:

我遇到了类似的问题,在5.4上用逗号分隔的电子邮件。这是我解决它的方式:

In your request class, override the prepareForValidation() method (which does nothing by default, btw), and explode your comma separated string.

在您的请求类中,覆盖prepareForValidation()方法(默认情况下不执行任何操作,顺便说一下),然后展开逗号分隔的字符串。

/**
 * @inheritDoc
 */
protected function prepareForValidation()
{
    $this->replace(['keywords' => explode(',', $this->keywords)]);
}

Now you can just use Laravel's normal array validation!

现在您可以使用Laravel的常规数组验证!

Since my case needed to be a bit more explicit on the messages, too, I added in some attribute and message customizations as well. I made a gist, if that's of interest to you as well

由于我的案例需要对消息更加明确,我也添加了一些属性和消息自定义。如果您对此感兴趣的话,我也会提出一个要点

#2


1  

It's not a good practice to override the all() method to validate a field.

覆盖all()方法来验证字段不是一个好习惯。

If you receive a comma separated String and not an array that you want to validate, but there is no common Method available, write your own.

如果您收到逗号分隔的String而不是要验证的数组,但没有可用的常用方法,请编写自己的方法。

in your App/Providers/ValidatorServiceProvider just add a new Validation:

在您的App / Providers / ValidatorServiceProvider中添加一个新的验证:

public function boot()
{
    Validator::extend('keywords', function ($attribute, $value, $parameters, $validator)
    {
        // put keywords into array
        $keywords = explode(',', $value);

        foreach($keywords as $keyword)
        {
            // do validation logic
            if(strlen($keyword) < 3)
            {
                return false;
            }
        }

        return true;
    }
}

Now you can use this Validation Rule on any request if needed, it is reusable.

现在,您可以根据需要对任何请求使用此验证规则,它是可重用的。

public function rules()
{
    $rules = [
        'title'       => 'required|min:3|unique:subdomain_categories,title|unique:subdomain_keywords,keyword',
        'description' => 'nullable',
        'image'       => 'required|image',
        'keywords'    => 'keywords',
    ];

    return $rules;
}

If the validation pass and you want to make the keywords be accessible in your request as array, write your own method:

如果验证通过并且您希望在请求中将关键字作为数组访问,请编写您自己的方法:

public function keywords ()
{
    return explode(',', $this->get('keywords'));
}

#1


2  

I was running into a similar problem with comma separated emails on 5.4. Here's how I solved it:

我遇到了类似的问题,在5.4上用逗号分隔的电子邮件。这是我解决它的方式:

In your request class, override the prepareForValidation() method (which does nothing by default, btw), and explode your comma separated string.

在您的请求类中,覆盖prepareForValidation()方法(默认情况下不执行任何操作,顺便说一下),然后展开逗号分隔的字符串。

/**
 * @inheritDoc
 */
protected function prepareForValidation()
{
    $this->replace(['keywords' => explode(',', $this->keywords)]);
}

Now you can just use Laravel's normal array validation!

现在您可以使用Laravel的常规数组验证!

Since my case needed to be a bit more explicit on the messages, too, I added in some attribute and message customizations as well. I made a gist, if that's of interest to you as well

由于我的案例需要对消息更加明确,我也添加了一些属性和消息自定义。如果您对此感兴趣的话,我也会提出一个要点

#2


1  

It's not a good practice to override the all() method to validate a field.

覆盖all()方法来验证字段不是一个好习惯。

If you receive a comma separated String and not an array that you want to validate, but there is no common Method available, write your own.

如果您收到逗号分隔的String而不是要验证的数组,但没有可用的常用方法,请编写自己的方法。

in your App/Providers/ValidatorServiceProvider just add a new Validation:

在您的App / Providers / ValidatorServiceProvider中添加一个新的验证:

public function boot()
{
    Validator::extend('keywords', function ($attribute, $value, $parameters, $validator)
    {
        // put keywords into array
        $keywords = explode(',', $value);

        foreach($keywords as $keyword)
        {
            // do validation logic
            if(strlen($keyword) < 3)
            {
                return false;
            }
        }

        return true;
    }
}

Now you can use this Validation Rule on any request if needed, it is reusable.

现在,您可以根据需要对任何请求使用此验证规则,它是可重用的。

public function rules()
{
    $rules = [
        'title'       => 'required|min:3|unique:subdomain_categories,title|unique:subdomain_keywords,keyword',
        'description' => 'nullable',
        'image'       => 'required|image',
        'keywords'    => 'keywords',
    ];

    return $rules;
}

If the validation pass and you want to make the keywords be accessible in your request as array, write your own method:

如果验证通过并且您希望在请求中将关键字作为数组访问,请编写您自己的方法:

public function keywords ()
{
    return explode(',', $this->get('keywords'));
}