From the vendor code at vendor\laravel\framework\src\Illuminate\Contracts\Validation\Rule.php, the interface Illuminate\Contracts\Validation\Rule is now deprecated.
namespace Illuminate\Contracts\Validation;
/**
* @deprecated see ValidationRule
*/
interface Rule
{
....
The interface Illuminate\Contracts\Validation\ValidationRule is now recommended for creating custom validation rules. So, to modify @Luigel's answer, the up-to-date implementation that is tested in Laravel 10 is:
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule as Rule;
class CustomFileRule implements Rule
{
protected array $acceptableTypes = [];
public function __construct(array $acceptableTypes = [])
{
$this->acceptableTypes = $acceptableTypes;
}
/**
* @param string $attribute
* @param \Illuminate\Http\UploadedFile $value
*
* @return void
*/
public function validate($attribute, $value, Closure $fail) : void
{
if(!in_array($value->getClientOriginalExtension(), $this->acceptableTypes))
{
$fail('Invalid document type uploaded');
}
}
}
Notice that it uses the Closure feature of PHP introduced in PHP 5.3 to report error messages.
The instantiation of the class remains the same:
[
'rules' => ['required', new App\Rules\CustomFileRule(['pdf,bdoc,asice,png,jpg'])]
]
NB: Take care to set the encoding type of your form to enctype="multipart/form-data" before testing this.