Laravel FormRequest Validation:如果非必需字段验证失败,则将该值更改为null并继续

时间:2018-10-31 18:17:09

标签: php validation laravel-5

我正在将Laravel 5.5与FormRequest Validation一起使用。我当前的代码如下。这用于验证来自请求的数据。

如果可为空的字段在请求中的验证失败,则我希望请求继续,并将该字段的值设置为NULL。因此,例如,如果count是作为字符串而不是整数发送的。我想将count的值设为NULL并继续进行请求。

是否可以使用此FormRequest?如果可以,怎么办?

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Response;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class FieldsCheck extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'userid' => 'required|integer',
            'custom' => 'nullable|string|max:99',
            'count' => 'nullable|integer'

        ];
    }


    protected function failedValidation(Validator $validator)
    {
        // if it fails validation, is there a way to change the failing value to null here and continue with the request?
    }

}

1 个答案:

答案 0 :(得分:0)

执行此操作的几个步骤。

  1. 已准备好要更改其值的字段的数组。
  2. 对验证器上的每个循环运行a,以将字段与您在步骤1中创建的数组进行匹配。
  3. 如果验证失败并匹配数组,请使用$this->merge([$key => null])将请求值覆盖为空。
  4. 如果验证失败并且与数组不匹配,请使用throw new HttpResponseException发回验证错误。

下面是一些带有注释的示例代码:

protected function failedValidation(Validator $validator)
{
    $fields_to_null = ['count', 'custom']; // array of fields that should be changed to null if failed validation
    foreach($validator->errors()->getMessages() as $key => $msg) {
        // if fails validation && key exists in the array, change the field's value null and continue
        if (in_array($key, $fields_to_null)) {
            $this->merge([$key => null]);
        } else {
            // https://laracasts.com/discuss/channels/laravel/how-make-a-custom-formrequest-error-response-in-laravel-55?page=1
            // if an error does not match a field in the array, return validation error
            throw new HttpResponseException(response()->json($msg[0]),422); 
        }
    }
}

该请求将继续发送到控制器,除非命中throw new httpResponseException