Validate React forms in Symfony 5
If you develop web applications with Symfony and recently learned React, then this may be of help.
We’re going to build a sign up form in React that has 3 inputs, fullname, email and password and look at how we can validate it using the Symfony Validator component.
The Validator component is used to validate objects and can be used in non-symfony projects. Refer to the documentation.
The code below is using Symfony 5, however it should work in Symfony 4 and 3 by making small adjustments.
Let’s get started
Create a basic index.html.twig file and write a div
with id
of form
for use with React. Feel free to use PHP templates instead of Twig.
Usually in Symfony we create forms in form classes, but we won’t do that because we’re going to create a form component in React and render it, this will be a controlled component since we’re going to manage the form inputs’ states in React.
The above component is pretty simple,
- it renders a form element with 3 inputs named fullname, email and password.
- it has 2 event handlers,
handleChange()
andhandleSubmit()
. ThehandleChange()
method will keep track of every change on the inputs and keeping the component’s state updated, while thehandleSubmit()
method will handle the form submission. - When the form is submitted, we are making an ajax request to our back-end and sending the form data stored in the state along.
Create Entity form class
Now we’re going to create the entity form class that will hold the form data and perform some validation using constrains.
The class resembles our form, it has fullname, email and password properties with some validation, it also contains some setter and getter methods for easy access.
Validate and persist data
Now what’s left is to receive the data from the request and perform some validation.
Normally in Symfony we don’t directly deal with the validator as the Symfony Form Component handles that for us. But since we’re creating our form in React we need to use the Validator component to validate our form data.
- in lines 19 - 22, we create a new instance of the SignUp Class and set the form data that’s coming from the request to the respected properties.
- 26 - 28, we validate each property individually by passing the object and the property name to the
validateProperty()
method. - 30 - 41, we check if there are any errors that are returned from the validation, if there are return a JSON response with errors.
- 42 - 50, if there are no errors, it means that the form data is valid, persist the data to the database and return a JSON response.