I'm trying to validate an array of files I have in Laravel and Livewire v3. I've written up the validation rules for my properties and hit a roadblock here:
#[Validate(["files" => ["array", "max:5"], "files.*" => ["image", "mimes:jpg,bmp,png"]])]
public array $files = [];
The validation works fine, however I am struggling on changing the error message to use an alias on array elements that have been validated:
The files.0 field must be a file of type: png, jpg.
Is the message I get, but I am trying to change it to:
The file field must be a file of type: png, jpg.
I've managed to achieve that when not validating an array like this:
#[Validate(["required", "string", "min:10"], as: "question")]
public ?string $question;
I've also tried changing the validation attributes like this, too:
protected array $validationAttributes = [
"files.0" => "file",
"files.1" => "file",
"files.2" => "file",
"files.3" => "file",
"files.4" => "file"
];
but can't get it to work on files mentioned above.
Does anyone know if this is possible, or should I rewrite validation to be like it was in Livewire v2?
EDIT: I've done some experimentation as suggested by one of the answers:
#[Validate(["files.*" => ["image", "mimes:jpg,bmp,png"]], message: "The file field must be a file of type: png, jpg")]
public array $files = [];
Seems to throw an Array to string conversion
exception if "files.*"
validation array has more than one rule.
After reducing the validation rules to just mimes, the exception went away, but the message still was not applied.
You could achieve that like this by editing the validation message
#[Validate(["files" => ["array", "max:5"], "files.*" => ["image", "mimes:jpg,bmp,png"]], message: ['The file field must be a file of type: png, jpg'])]
public array $files = [];
or for more cleaner way you could write it like this
#[Validate(["files" => ["array", "max:5"]])]
#[Validate(["files.*" => ["image", "mimes:jpg,bmp,png"]], message: ['The file field must be a file of type: png, jpg'])]
public array $files = [];
for more info check Custom validation message