如何在Symfony Forms中验证上传的文件名?

问题描述 投票:1回答:1

以下是我在FormUploaderType的构建器中输入的 "条款"。

    ->add('terms', FileType::class, [
        'constraints'   => [
            'pattern'   => '/([a-z]+-)+[20]\d{7}\.pdf/',
            'message'   => 'Change the name of the file',
            'mimeTypes' => [
                "application/pdf",
                "application/x-pdf",
            ],
    ])

我想确定文件的名字是否和我想要的一样(例如:'something-else-in-here-20200430.pdf'),但它没有工作--它显示了一个错误信息......我如何处理它?我从symfony文档中看到了Annotation方法,也看到了类实体中的loadValidatorMetadata方法,但它们似乎都不能对我的文件上传起作用。

php forms symfony validation file-upload
1个回答
0
投票

你需要实例化这些约束。该 mimeTypes 键对应的是 File 约束,而 pattern 是为 Regex.

然而,由于 terms 是一个 UploadedFile,其 __toString() 方法将返回临时上传的文件名,检查将失败。你需要使用一个 Callback 而不是为了能够访问对象。

->add('terms', FileType::class, [
    'constraints'   => [
        new Callback(function ($object, ExecutionContextInterface $context, $payload) {
            $pattern = '/^([a-z]+-)+-20\d{6}\.pdf$/';
            if (!preg_match($pattern, $object->getClientOriginalName())) {
                $context->buildViolation('Change the name of the file')
                    ->addViolation();
            }
        }),
        new File([
            'mimeTypes' => [
                "application/pdf",
                "application/x-pdf",
            ],
        ]),
])
© www.soinside.com 2019 - 2024. All rights reserved.