在 Laravel 5.1 上进行验证之前修改输入
2022-08-30 20:35:50
我正在尝试在验证成功之前修改用户提交的输入。我已经遵循了这个简单的说明,但是当我在Laravel 5.1上测试它时,它不起作用。我做错了什么吗?
这是我的请求类SSHAM\Http\Requests\UserCreateRequest.php
<?php
namespace SSHAM\Http\Requests;
use SSHAM\Http\Requests\Request;
class UserCreateRequest extends Request
{
// Some stuff not related with this problem
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
// Only for debug
$prova = $this->all();
echo "<pre>Inside Request - Before sanitize\n[" . $prova['public_key'] . "]</pre>\n";
// Call a function to sanitize user input
$this->sanitize();
// Only for debug
$prova = $this->all();
echo "<pre>Inside Request - After sanitize\n[" . $prova['public_key'] . "]</pre>\n";
return [
'username' => 'required|max:255|unique:users',
'public_key' => 'openssh_key:public',
];
}
/**
* Sanitizes user input. In special 'public_key' to remove carriage returns
*/
public function sanitize()
{
$input = $this->all();
// Removes carriage returns from 'public_key' input
$input['public_key'] = str_replace(["\n", "\t", "\r"], '', $input['public_key']);
$this->replace($input);
}
}
这是我的自定义验证规则SSHAM\Providers\OpenSSHKeyValidatorServiceProvider.php
<?php
namespace SSHAM\Providers;
use Illuminate\Support\ServiceProvider;
class OpenSSHKeyValidatorServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
// Registering the validator extension with the validator factory
\Validator::extend('openssh_key', function ($attribute, $value, $parameters) {
// Some stuff not related with this problem
// Only for debug
echo "<pre>Inside Validator value\n[" . $value ."]</pre>\n";
dd();
return true;
});
}
// Some stuff not related with this problem
}
当我调用调试时,我得到这个输出:
Inside Request - Before sanitize
[blah
second line
third line]
Inside Request - After sanitize
[blah second line third line]
Inside Validator value
[blah
second line
third line]
似乎正在工作,但是当在验证类上处理值时,它尚未被清理。sanitize()