嵌套数组验证拉拉维尔编辑

2022-08-30 12:54:20

我正在构建一个基于 REST 的 API,其中一个 API 具有以下请求

{
   "categories_id" :"1",
   "product_name" : "Pen",
   "product_description" : "this is pen",
   "tags" : "pen,write",
   "image_count" : "4",
   "skus": 
      {
          "is_shippable":"n",
          "actual_price":"100.55", 
          "selling_price":"200.45",
          "quantity_type":"bucket",
          "quantity_total":"10",
          "bucket_value":"instock",
          "sort_order":"1"
      }
}

这些是我的验证规则

protected $rules = [
        ValidatorInterface::RULE_CREATE => [
        'users_id' => 'required',
        'user_profiles_id' => 'required',
        'categories_id' => 'required',
        'product_name' => 'required|max:100',
        'product_description' => 'required|max:1000',
        'tags' => 'required',
        'image_count'=>'required|integer',
        'creation_mode'=>'required|integer',
        'skus.is_shippable'=>'in:y,n',
        'skus.actual_price'=>'regex:/^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$/',
        'skus.selling_price' => 'regex:/^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$/',
        'skus.quantity_type' => 'sometimes|required|in:finite,infinite,bucket',
        'skus.quantity_total' => 'integer|required_if:skus.quantity_type,finite', 
        'skus.bucket_value'=>'in:instock,soldout,limited|required_if:skus.quantity_type,bucket',
        'skus.sort_order'=> 'required|integer'
        ],
        ValidatorInterface::RULE_UPDATE => [
        ]
    ];

上述请求已正确得到验证。但是 skus 内部可以有多个实体,如下请求所示

{
       "categories_id" :"1",
       "product_name" : "Pen",
       "product_description" : "this is pen",
       "tags" : "pen,write",
       "image_count" : "4",
       "skus": 
          [{
              "is_shippable":"n",
              "actual_price":"100.55", 
              "selling_price":"200.45",
              "quantity_type":"bucket",
              "quantity_total":"10",
              "bucket_value":"instock",
              "sort_order":"1"
          },
          {
              "is_shippable":"n",
              "actual_price":"100.55", 
              "selling_price":"200.45",
              "quantity_type":"bucket",
              "quantity_total":"10",
              "bucket_value":"instock",
              "sort_order":"1"
          }]
    }

如何验证是否存在多个嵌套实体?


答案 1

您使用的是哪个版本的Laravel?如果您使用的是Laravel 5.2,或者您不介意更新到它,那么有一个开箱即用的解决方案。

阵列验证

在 Laravel 5.2 中,验证数组表单输入字段要容易得多。例如,若要验证给定数组输入字段中的每封电子邮件是否唯一,可以执行以下操作:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users'
]);

同样,在语言文件中指定验证消息时,可以使用 * 字符,这样对基于数组的字段使用单个验证消息就变得轻而易举了:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique e-mail address',
    ]
],

Laravel新闻的另一个例子:

假设您有一个包含输入字段数组的表单,如下所示:

<p>
<input type="text" name="person[1][id]">
<input type="text" name="person[1][name]">
</p>
<p>
<input type="text" name="person[2][id]">
<input type="text" name="person[2][name]">
</p>

在 Laravel 5.1 中,要添加验证规则,需要循环访问并单独添加规则。而不是不得不做所有的事情,它已经被“Laravelized”变成了这个:

$v = Validator::make($request->all(), [
  'person.*.id' => 'exists:users.id',
  'person.*.name' => 'required:string',
]);

因此,如果您不想使用Laravel 5.2,则必须手动执行此操作,如果您更新到Laravel 5.2,则可以使用新的数组验证,它将如下所示:

protected $rules = [
        ValidatorInterface::RULE_CREATE => [
        'users_id' => 'required',
        'user_profiles_id' => 'required',
        'categories_id' => 'required',
        'product_name' => 'required|max:100',
        'product_description' => 'required|max:1000',
        'tags' => 'required',
        'image_count'=>'required|integer',
        'creation_mode'=>'required|integer',
        'skus.*.is_shippable'=>'in:y,n',
        'skus.*.actual_price'=>'regex:/^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$/',
        'skus.*.selling_price' => 'regex:/^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$/',
        'skus.*.quantity_type' => 'sometimes|required|in:finite,infinite,bucket',
        'skus.*.quantity_total' => 'integer|required_if:skus.quantity_type,finite', 
        'skus.*.bucket_value'=>'in:instock,soldout,limited|required_if:skus.quantity_type,bucket',
        'skus.*.sort_order'=> 'required|integer'
        ],
        ValidatorInterface::RULE_UPDATE => [
        ]
    ];

编辑

Ihmo 添加此额外验证逻辑的最佳方法是扩展 Validator 类,创建 CustomValidator 类,这可能有点过分,但是当 Laravel 5.2 发布时,您可以删除 CustomValidator 并继续使用 Laravel 的 5.2 Validator,而无需对代码进行任何更改。

如何?好吧,首先,我们在我决定命名此文件夹 Validator 下创建一个文件夹,您可以随意命名它,只需记住更新以下类的命名空间即可。接下来,我们将在此文件夹 CustomValidator.php,CustomValidatorServiceProvider.phpFactory.php中创建 3.php文件。app/

自定义验证器.php

<?php

namespace App\Validator;

use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Validation\Validator;
use Symfony\Component\Translation\TranslatorInterface;

class CustomValidator extends Validator
{
    /**
     * Create a new Validator instance.
     *
     * @param  \Symfony\Component\Translation\TranslatorInterface  $translator
     * @param  array  $data
     * @param  array  $rules
     * @param  array  $messages
     * @param  array  $customAttributes
     * @return void
     */
    public function __construct(TranslatorInterface $translator, array $data, array $rules, array $messages = [], array $customAttributes = [])
    {
        $this->translator = $translator;
        $this->customMessages = $messages;
        $this->data = $this->parseData($data);
        $this->customAttributes = $customAttributes;

        // Explode the rules first so that the implicit ->each calls are made...
        $rules = $this->explodeRules($rules);

        $this->rules = array_merge((array) $this->rules, $rules);
    }

    /**
     * Explode the rules into an array of rules.
     *
     * @param  string|array  $rules
     * @return array
     */
    protected function explodeRules($rules)
    {
        foreach ($rules as $key => $rule) {
            if (Str::contains($key, '*')) {
                $this->each($key, $rule);
                unset($rules[$key]);
            } else {
                $rules[$key] = (is_string($rule)) ? explode('|', $rule) : $rule;
            }
        }
        return $rules;
    }


    /**
     * Define a set of rules that apply to each element in an array attribute.
     *
     * @param  string  $attribute
     * @param  string|array  $rules
     * @return void
     *
     * @throws \InvalidArgumentException
     */
    public function each($attribute, $rules)
    {
        $data = Arr::dot($this->data);
        foreach ($data as $key => $value) {
            if (Str::startsWith($key, $attribute) || Str::is($attribute, $key)) {
                foreach ((array) $rules as $ruleKey => $ruleValue) {
                    if (! is_string($ruleKey) || Str::endsWith($key, $ruleKey)) {
                        $this->mergeRules($key, $ruleValue);
                    }
                }
            }
        }
    }



    /**
     * Get the inline message for a rule if it exists.
     *
     * @param  string  $attribute
     * @param  string  $lowerRule
     * @param  array   $source
     * @return string|null
     */
    protected function getInlineMessage($attribute, $lowerRule, $source = null)
    {
        $source = $source ?: $this->customMessages;
        $keys = ["{$attribute}.{$lowerRule}", $lowerRule];
        // First we will check for a custom message for an attribute specific rule
        // message for the fields, then we will check for a general custom line
        // that is not attribute specific. If we find either we'll return it.
        foreach ($keys as $key) {
            foreach (array_keys($source) as $sourceKey) {
                if (Str::is($sourceKey, $key)) {
                    return $source[$sourceKey];
                }
            }
        }
    }

    /**
     * Get the custom error message from translator.
     *
     * @param  string  $customKey
     * @return string
     */
    protected function getCustomMessageFromTranslator($customKey)
    {
        $shortKey = str_replace('validation.custom.', '', $customKey);
        $customMessages = Arr::dot(
            (array) $this->translator->trans('validation.custom')
        );
        foreach ($customMessages as $key => $message) {
            if ($key === $shortKey || (Str::contains($key, ['*']) && Str::is($key, $shortKey))) {
                return $message;
            }
        }
        return $customKey;
    }
}

此自定义验证器具有在Laravel 5.2上所做的所有更改,您可以在此处进行检查

现在,由于我们有一个新的 CustomValidator 类,我们必须找到一种使用它的方法,为此我们必须扩展 ValidatorServiceProviderValidator 工厂

CustomValidatorServiceProvider.php

<?php

namespace App\Validator;


class CustomValidatorServiceProvider extends \Illuminate\Validation\ValidationServiceProvider
{
    /**
     * Register the validation factory.
     *
     * @return void
     */
    protected function registerValidationFactory()
    {
        $this->app->singleton('validator', function ($app) {
            $validator = new Factory($app['translator'], $app);

            // The validation presence verifier is responsible for determining the existence
            // of values in a given data collection, typically a relational database or
            // other persistent data stores. And it is used to check for uniqueness.
            if (isset($app['validation.presence'])) {
                $validator->setPresenceVerifier($app['validation.presence']);
            }

            return $validator;
        });
    }
}

工厂.php

<?php

namespace App\Validator;

use App\Validator\CustomValidator as Validator;

class Factory extends \Illuminate\Validation\Factory
{
    /**
     * Resolve a new Validator instance.
     *
     * @param  array  $data
     * @param  array  $rules
     * @param  array  $messages
     * @param  array  $customAttributes
     * @return App\Test\CustomValidator
     */
    protected function resolve(array $data, array $rules, array $messages, array $customAttributes)
    {
        if (is_null($this->resolver)) {
            return new Validator($this->translator, $data, $rules, $messages, $customAttributes);
        }

        return call_user_func($this->resolver, $this->translator, $data, $rules, $messages, $customAttributes);
    }
}

现在我们已经扩展了验证以支持嵌套语法sku.*.id

我们只需要将验证器交换到我们的CustomValidator,最后一步是更改文件配置/应用程序.php并在ServiceProviders数组中查找VeristatorServiceProvider,只需注释该行并添加我们的扩展服务提供商,如下所示:

....
// Illuminate\Validation\ValidationServiceProvider::class,
App\Validator\CustomValidatorServiceProvider::class,
....

我们注释掉它的原因是,每当您将Laravel 5.1更新到5.2时,您只想取消注释它,从列表中删除我们的CustomValidatorServiceProvider,然后删除我们的app/ Validator文件夹,因为我们不再需要它了。


答案 2

推荐