In my last blog Integrate redux-form in your React App – Part 1 I explained how to integrate redux-form in our react-app. Now in this part, we will learn how to validate our redux-from.

We use Field component from redux-form to build our form. The Field component is how you connect each individual input to the Redux store. Let’s see how to achieve Field-level validation in redux-form.

We start with our “First Name” text field component.

To apply validation on firstName field, we have to define a validation function in our form. The parameters to the validation function are,

  • value – The current value of the field
  • allValues – The values of the entire form
  • props – Any props passed to the form

If the value is valid, the validation function should return undefined.

If the value is invalid, the validation function should return an error.

Our validate Function should look like following.

In our validate function, it takes one parameter values, which is an object of form’s values. So now we are checking if our firstName is empty or not.

Now we have to give our validate function to redux-form as following.

export default reduxForm({form: 'simple', validate})(SimpleForm);

Now It’s time to refactor our form’s text field component as following.

Inthe above code, we use meta props of redux-form’s Field component. The props under the meta key are metadata about the state of this field that redux-form is tracking for you. Here we use two meta props touch and error,

  1. touch: it returns true if the field has been touched. By default, this will be set when the field is blurred.
  2. error: The error for this field if its value is not passing validation.

for more details of meta props, refer the following link:

Redux Form The Field component is how you connect each individual input to the Redux store. There are three fundamental things… redux-form.com

Our First Name text field component should look as following,

So finally our SimpleForm.js Look like as following,

You can find the whole source code here.

References

  1. https://redux-form.com/7.4.2/examples/fieldlevelvalidation/
  2. https://redux-form.com/7.4.2/docs/api/field.md/

At BoTree Technologies, we build web and mobile applications to add value to our client’s business. We align ourselves to ensure that our client benefits the most out of our engagement.

We work in Ruby on RailsPython, Java, React, Android and iOS.

Drop us a line to discuss how can we help take your business to the next level.