Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question best practice] How do you handle invalid input type in forms? #1798

Open
acorbel opened this issue Nov 25, 2017 · 0 comments
Open

Comments

@acorbel
Copy link

acorbel commented Nov 25, 2017

Hi there,

I'm building a REST API with SF3.4 and FOSRestBundle and I use forms to filter and validate input data.

Here is an example:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', CoreType\TextType::class)
        ;
    }

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

And my form handler:

        $form = $formFactory->createForm(UserType::class, $user);
        $form->submit(array_intersect_key($request->request->all(), $form->all()), true); // delete extra fields
        if ($form->isValid()) ...

When I submit {"name": "test"}, it works well, but when I send {"name": ["test"]}, I get a Symfony\Component\Validator\Exception\UnexpectedTypeException.

Is there a best practice to protect REST apis from invalid input? For now, I just output this exception as 400 status code.

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant