You can create a custom validation rule that looks at the filename and does whatever checks you like. This example, as a closure, will check the filename length is within limits:
function (string $attribute, mixed $value, Closure $fail) {
$minLength = 5;
$maxLength = 200;
$filename = $value->getClientOriginalName();
if (strlen($filename) > $maxLength) {
$fail('The filename is too long. Please rename the file to a shorter name.');
}
if (strlen($filename) < $minLength) {
$fail('The filename is too short.');
}
}
It can be used anywhere you would use a validation rule or alias. For example in livewire to ensure myFile is not too large, is a CSV, and gthe filename is not too long or too short:
$this->validate([
'myFile' => [
'required',
File::types('csv', 'txt')->max(2 * 1024), // kB
function (string $attribute, mixed $value, Closure $fail) {
// ...as above...
},
],
]);
You can put your own arbitrary checks and messages in there.
You can put the rule into a class, and accept parameters to set the limits, if you are using it in multiple places. If you want to be really fancy you could nest the validation rules so you could use any of the other validation rules against the filename, such as min, max, regex.