我正在构建一个基于 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"
}]
}
如何验证是否有多个嵌套实体?
最佳答案
您使用的是什么版本的 Laravel?如果您使用 Laravel 5.2或者,如果您不介意更新到它,则有一个开箱即用的解决方案。
Array Validation
Validating array form input fields is much easier in Laravel 5.2. For example, to validate that each e-mail in a given array input field is unique, you may do the following:
$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users'
]);
Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:
'custom' => [
'person.*.email' => [
'unique' => 'Each person must have a unique e-mail address',
]
],
来自 Laravel news 的另一个示例:
Pretend you have a form with an array of input fields like this:
<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>
In Laravel 5.1 to add validation rules it required looping through and adding the rules individually. Instead of having to do all that it’s been “Laravelized” into this:
$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 而无需对您的代码进行任何更改。
如何?好吧,首先我们在 app/ 下创建一个文件夹,我决定将此文件夹命名为 Validator,您可以随意命名,只要记住更新以下类的命名空间即可。接下来,我们将在此文件夹中创建 3 个 .php 文件 CustomValidator.php、CustomValidatorServiceProvider.php 和 Factory.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 上所做的所有更改,您可以在 here 中查看它们
既然我们有一个新的 CustomValidator 类,我们必须找到一种使用它的方法,为此我们必须扩展 ValidatorServiceProvider 和 Validator 工厂。
<?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
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
我们只需要将 Validator 换成我们的 CustomValidator,最后一步是更改文件 config/app.php 并在 ServiceProviders 数组中查找 ValidatorServiceProvider ,只需注释该行并添加我们的扩展服务提供商,如下所示:
....
// Illuminate\Validation\ValidationServiceProvider::class,
App\Validator\CustomValidatorServiceProvider::class,
....
我们将其注释掉的原因是,每当您将 Laravel 5.1 更新到 5.2 时,您只想取消注释,从列表中删除我们的 CustomValidatorServiceProvider,然后删除我们的 app/Validator 文件夹,因为我们不再需要它了.
关于php - 嵌套数组验证 laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34393279/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby数组,我们在StackOverflow上找到一
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss