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.
CodePudding user response:
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\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->file->get('key'), $fileConstraints);
}
The method returns an iterator of constraints.