Search code examples
phpsymfonysymfony4symfony-forms

Validation is skipping when submit the form with rest api


I have this form :

    class RegistrationFormType extends AbstractType
    {
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', EmailType::class, [
                'constraints' => [
                    new NotBlank(),
                ]
            ])
            ->add('username')
            ->add('password')
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'app_user_register';
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
            'allow_extra_fields' => true,
            'csrf_protection' => false,
        ]);
    }
}

My api in controller :

/**
 * @Route("/api/register")
 * @Method("POST")
 * @param Request $request
 *
 * @return JsonResponse
 */
public function register(
    UserService $userService,
    Request $request
)
{
    try {
         return $userService->register(json_decode($request->getContent(), true));
    } catch (\Exception $e) {
        return $this->json([
            'status' => Response::HTTP_INTERNAL_SERVER_ERROR,
            'result' => $e->getMessage()
        ]);
    }
}

And my function in service :

public function register($formData)
{
    $user = new User();

    $form = $this->formFactory->create(RegistrationFormType::class, $user);
    $form->submit($formData);

    if ($form->isSubmitted() && $form->isValid()) {
        $this->entityManager->persist($user);
        $this->entityManager->flush();

        return new JsonResponse([
            'status' => Response::HTTP_OK,
            'result' => true
        ]);
    }

    return new JsonResponse([
        'status'    => Response::HTTP_BAD_REQUEST,
        'result'    => FormErrorFormatter::getErrorsFromForm($form)
    ]);
}

When I tried to call the api /api/register in postman with

{
    "username": "test1",
    "email": "test1",
    "password": "123456"
}

I get 200 code, but normally should drop an error because the email is not valid, as I put in form creation that the field email should be in the email format, even if I put an empty string in email I get the 200 code. So seems the validations is not working.


Solution

  • EmailType, as far as I can tell, has no default constraints. However, you override the constraints by demanding it's NotBlank which is definitely not the same as the Email constraint. the Form does add type="email" to the html, which the browser will enforce (which is technically unreliable, because the user can just turn it into a text field).

    Solution is probably to use the Email constraint and set the required property to true.