适用于JSON的Laravel验证规则

时间:2018-05-02 20:23:03

标签: json laravel validation

我正在尝试使用带有JSON格式数据验证规则的自定义FormRequest。如果我在控制器中使用相同的代码而不是FormRequest类,那么它工作正常,请参阅下文:

数组数据(来自ajax请求):

[
  {
    "name": "id",
    "value": "1"
  },
  {
    "name": "title",
    "value": "My fun project"
  }  
]

控制器:

public function update(Request $request, $id) {
    //convert it to readable json
    $jsonReq = $request->json()->all();
    $jsonData = array();
    foreach ($jsonReq as $json) {
        $jsonData[$json["name"]] = $json["value"];
    }

    $rules = [
        'id' => 'required|numeric:1',
        'title' => 'required|max:255',
    ];

    $validation = Validator::make($jsonData, $rules);

    if ($validation->fails()) {
      return $validation->errors();
    }
}

在控制器中使用时,以上工作正常。但是,我想在一个单独的类中分离我的验证,扩展FormRequest。这会产生一些错误,很可能是由于数组格式造成的。

class UpdateProjectValidationRequest extends FormRequest {

      public function rules() {

        $jsonReq = $this->json()->all();
        $jsonData = array();
        foreach ($jsonReq as $json) {
            $jsonData[$json["name"]] = $json["value"];
        }

        return [
            'id' => 'required|max:1', //does not work
            $jsonData['title'] => 'required|max:255', //does not work
        ];
}

控制器:

  public function update(UpdateProjectValidationRequest $request, $id) {

    // validate against rules
    $request->rules();

错误消息:

{
  "message": "The given data was invalid.",
  "errors": {
    "My fun project": [
      "My fun project field is required."
    ],
    "id": [
      "The id field is required."
    ],

显然,这与格式有关。任何想法如何解决这个问题?请注意,在foreach循环之后,数据格式化为:

{
  "id": "1",
  "title": "My Fun project",
}

1 个答案:

答案 0 :(得分:0)

好的,所以我无法使用laravel FormRequest解决它,而是通过将其序列化为json而不是数组来修改ajax调用本身。

    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
//old: var formdata = JSON.stringify(jQuery('#myForm').serializeArray());
var formdata = JSON.stringify(jQuery('#myForm').serializeObject());