validation - laravel : sanitize request data before validation

标签 validation laravel request rules

有一个UpdateUserRequest表单请求,用于根据rules mathod中定义的规则验证字段值。默认情况下,它具有rules()和authorize()方法。我想防止验证和更新空白字段(例如password)。

在规则中使用sometimes没什么用,因为html输入将出现在POST请求中,即使它们为空。

array:6 [▼
 "_method" => "PATCH"
 "_token" => "Cz79rRez2f6MG0tTU17nVwXD0X1lNGH1hA7OORjm"
 "name" => "john"
 "email" => "mymail@gmail.com"
 "password" => ""
 "password_confirmation" => ""

]

因此,在规则中使用sometimes之前,我应该删除POST请求的空键。
问题是:清除Request数组的最佳位置在哪里?
是否有任何laravel内置方法来管理此类情况?

P.S :解决方案:
@Bogdon解决方案仍然有效并且可行,但是here采用了另一种简单,简洁的解决方案:
只是在表单请求中覆盖all()方法
 class RegistrationRequest extends Request
  {

...

public function all()
{
    $attributes = parent::all();

    if(isset($attributes['password']) && empty($attributes['password'])) 
        {
            unset($attributes['password']);
        }
    $this->replace($attributes);

    return parent::all();

}

...

}

最佳答案

为了完成这项工作,您需要修改App\Http\Requests\Request类的内容,以提供一种清理输入的方法(从this Laracasts post提取的类代码):

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest
{
    /**
     * Validate the input.
     *
     * @param  \Illuminate\Validation\Factory  $factory
     * @return \Illuminate\Validation\Validator
     */
    public function validator($factory)
    {
        return $factory->make(
            $this->sanitizeInput(), $this->container->call([$this, 'rules']), $this->messages()
        );
    }

    /**
     * Sanitize the input.
     *
     * @return array
     */
    protected function sanitizeInput()
    {
        if (method_exists($this, 'sanitize'))
        {
            return $this->container->call([$this, 'sanitize']);
        }

        return $this->all();
    }
}

之后,您只需要在sanitize类中编写add UpdateUserRequest方法即可,该方法会在输入为空时从输入中删除password字段:

public function sanitize()
{
    if (empty($this->get('password'))) {
        // Get all input
        $input = $this->all();
        // Remove the password field
        unset($input['password']);
        // Replace the input with the modified one
        $this->replace($input);
    }

    return $this->all();
}

现在,将sometimes规则用于密码字段将起作用:

public function rules()
{
    return [
        // Other rules go here
        'password' => 'sometimes|required|confirmed'
    ];
}

关于validation - laravel : sanitize request data before validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35562994/

相关文章:

php - 获取特定值 Laravel

php - 我该如何解决 "laravel/horizon v1.1.0 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system"?

sql - 为什么 hasOne 关系中的外键需要位于引用表中?

session - 从 JSF 页面获取请求和 session 参数及属性

regex - 英国电话号码正则表达式 - 没有空格或括号

javascript - 电子邮件地址验证的最佳做法(包括 gmail 地址中的 +)

javascript - 防止移动设备中的输入类型编号为 "DOT"

c# - 如果验证方法应该返回验证结果,为什么会有 ArgumentException 类?

java - 如何在 REST Web 服务服务器端接收 "Accept" header

ios - URL 请求中发送页面编号问题。获得成功但结果空洞