How to use Symfony validation with json data

Viewed 2566

When I'm using Symfony v5.1 array of collection validation I got a strange response.

This is my code

   $constraint = new Assert\Collection([
        'email' => new Assert\Email(),
        'password' => new Assert\Length(['min' => 60]),
    ]);

    $violations = $validator->validate($request->request->all() , $constraint);

    foreach($violations as $violation)
    {
        $errors[] = [$violation->getPropertyPath() => $violation->getMessage()];
    }

    dd($errors);

and this is the result I got:

 array:5 [
  0 => array:1 [
    "[password]" => "This value is too short. It should have 60 characters or more."
  ]
  1 => array:1 [
    "[name]" => "This field was not expected."
  ]
  2 => array:1 [
    "[phone_number]" => "This field was not expected."
  ]
  3 => array:1 [
    "[username]" => "This field was not expected."
  ]
  4 => array:1 [
    "[role_id]" => "This field was not expected."
  ]
]

so I'm wondering why the name of the input is swapping in array[] [name] so is there is a wrong something I did?

And why Symfony is focused on entity validation and not on the request like Laravel framework?

1 Answers

I found a really package implementing what I need, it just works like as Laravel and validates the request so easy https://github.com/fesor/request-objects but it is not working on Symfony 5 so I upgraded it to be compatible with v5 wit some changes https://github.com/TheGeekyM/symfony-object-request-validation.

you just call the request in the controlled

namespace App\Controlles;

public function registerUserAction(RegisterUserRequest $request)
{
    // Do Stuff! The data is already validated!
}

and this is the request with the validations

use Fesor\RequestObject\RequestObject;
use Symfony\Component\Validator\Constraints as Assert;

class RegisterUserRequest extends RequestObject
{
    public function rules()
    {
        return new Assert\Collection([
            'email' => new Assert\Email(['message' => 'Please fill in valid email']),
            'password' => new Assert\Length(['min' => 4, 'minMessage' => 'Password is to short']),
            'first_name' => new Assert\NotNull(['message' => 'Please provide your first name']),
            'last_name' => new Assert\NotNull(['message' => 'Please provide your last name'])
        ]);
    }
}

and that is it, enjoy

Related