我尝试了一些验证规则,例如:Boolean和Requiredfile以及nested array字段,但总是失败
例如,我尝试像这样创建表单请求:
<?php
namespace App\Http\Requests\Test;
use Illuminate\Foundation\Http\FormRequest;
class Test extends FormRequest
{
public function validationData()
{
return [
'booleanField' => $this->boolean("booleanField"),
'fileField' => $this->boolean("fileField"),
'arrayField' => $this->input("arrayField"),
'arrayField.*.booleanField' => $this->boolean("arrayField.*.booleanField"),
'arrayField.*.fileField' => $this->file("arrayField.*.fileField"),
];
}
public function rules(): array
{
return [
"booleanField" => ["required", "boolean"], // <= works as expected
"fileField" => ["required", "file", "mimes:jpg,png,jpeg,docx,xlsx,zip", "max:5120"], // <= works as expected
"arrayField" => ["required", "array"],
"arrayField.*.booleanField" => ["required", "boolean"], // <= not working, always returning error "The arrayField.0.booleanField field must be true or false."
"arrayField.*.fileField" => ["required", "file", "mimes:jpg,png,jpeg,docx,xlsx,zip", "max:5120"], // <= not working, always returning error "The arrayField.0.fileField is required."
];
}
}
这就是我发现的。我不知道其他规则是否也不起作用。
Laravel 版本 11.31.0。 谢谢你。
来自#53489
的重复问题方法
validationData
应该是 you 访问将要验证的数据的一种方式。它并不意味着覆盖数据。
当
FormRequest
被解析时,应用程序(或容器,如果您愿意)将调用其 validateResolved
方法。
public function validateResolved()
{
$this->prepareForValidation();
if (! $this->passesAuthorization()) {
$this->failedAuthorization();
}
$instance = $this->getValidatorInstance();
if ($this->isPrecognitive()) {
$instance->after(Precognition::afterValidationHook($this));
}
if ($instance->fails()) {
$this->failedValidation($instance);
}
$this->passedValidation();
}
如果您想修改即将验证的数据,您正在寻找的方法是
prepareForValidation
。据我所知,你不能像通配符一样使用 * 。
class Test extends FormRequest
{
/**
* Prepare the data for validation.
*
* @return void
*/
public function prepareForValidation(): void
{
// please check this and make sure the data you're sending looks like the data you're trying to validate.
dd($this->validationData());
$this->merge([
'key' => 'value,
...
]);
}
...
}