4

Validate an input field of HTML form is a simple operation, as follows:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;

    public function adminPassword(Request $request) 
    {
        $this->parameters = $request->request->all();
           ...
        $new_password = $this->parameters['new_password'];
        $validator = Validation::createValidator();
        $violations = $validator->validate($new_password, [
            new Assert\Length([
                'min' => 4
            ])
        ]);
        if (0 !== count($violations)) {
            ...
        }
           ...
    }

Can validation request of HTML form file upload (image), can be done by Symfony in the same simple way?

public function logoUpload(Request $request)
{
     $file = $request->files->get('logo');
     ...
}

The requirement is not using Twig, or Symfony 'Form' ('createFormBuilder'), as not done above.

1 Answer 1

6

In Symfony, the result of $request->files->get('key') is an UploadedFile or null.

With an UploadedFile you can use your validator with a file constraint as the example below :

use Symfony\Component\Validator\Constraints\File; 
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validation;

...

public function validateFile(Request $request): ConstraintViolationListInterface
{
   $fileConstraints = new File([
       'maxSize' => '64M',
       'maxSizeMessage' => 'The file is too big',
       'mimeTypes' => ['pdf' => 'application/pdf'],
       'mimeTypesMessage' => 'The format is incorrect, only PDF allowed'
   ]);

   $validator = Validation::createValidator();
   
   return $validator->validate($request->files->get('key'), $fileConstraints);
}

The method returns an iterator of constraints.

Please note to use MimeTypes you need to install symfony/mime on your app

Sign up to request clarification or add additional context in comments.

6 Comments

In '.. = new File([...])' I'm getting error 'Expected type 'string'. Found 'string[]''?
It seems we don't have the same constructor for this constraints, which version of Symfony are you using ? Can you send me the constructor signature of your 'File' constraints please ?
I use standalone Symfony components in my app. Based on 'Kernel.php' public const VERSION = '6.1.4'; __construct()
I changed to '..\Constraints\File; ' it was ' ../HttpFoundation\File\File;'. Also, please note $file is '..->files->get('logo')', not '..->file' (plural), now I'm getting the following error message: "You cannot guess the mime type as the Mime component is not installed. Try running "composer require symfony/mime".
After running "composer require symfony/mime" I got the validation to work, Thx.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.