使用Respect Validation验证JSON数组

时间:2017-04-05 09:17:23

标签: json validation respect-validation

我有以下JSON:

{
    "articles":[
        {"amount": 3, "vat": 19},
        {"amount": 2, "vat": 7}
    ]
}

我想验证文章是一个数组,密钥数量是一个数字,还是作为一个数字。我正在尝试以下方法:

'articles' => v::arrayType()->keySet(
                        v::key('amount', v::intVal()),
                        v::key('vat', v::intVal())
                    )

结果我得到了:

{"articles":["Must have keys { \"amount\", \"vat\" }"]}}

我在这里做错了什么?我认为它应该做的工作:https://github.com/Respect/Validation/blob/master/docs/KeySet.md

谢谢!

修改

这是我正在使用的验证代码以及我检索JSON的方式(在请求对象中):

public function validate($request, array $rules)
    {
      foreach ($rules as $field => $rule) {
        try{
          $rule->setName(ucfirst($field))->assert($request->getParam($field));
        } catch(NestedValidationException $e){
          $this->errors[$field] = $e->getMessages();
        }
      }
      $this->ret['error'] = "Validation Error";
      $this->ret['errornr'] = 600;
      $this->ret['fields'] = $this->errors;
      return $this;
    }


$validation = $this->validator->validate($request, [
      'paymentmethod' => v::notEmpty(),
      'memberid' => v::notEmpty()->intVal(),
      'articles' => v::arrayVal()
    ]);

0 个答案:

没有答案