⚠️ This lesson is retired and might contain outdated information.

Add Synchronous Validation to a redux-form using field-level Validation

Rory Smith
InstructorRory Smith
Share this video with your friends

Social Share Links

Send Tweet

There are two ways to handle validation in redux-form. In this example, we are going to find out how to use field-level-validation using reusable functions, which presents a clean, readable syntax attached to each redux-form Field element.

Instructor: [00:00] In our form currently, we're using a validation function to provide synchronous validation to our form. This involves creating an errors object, and adding values to the object corresponding to the names of fields in our form, and we just return the errors object at the end.

[00:25] Using Redux Form is another approach to validation, so let's refactor our app so far so that it uses field-level validation. Field-level validation involves passing functions into our fields, so instead of one large validate function, this file is going to contain several functions, each one dealing with a specific validation situation.

[00:52] We can have a required function, which takes a value. We'll return a ternary operator if there is a value, and we can return undefined as the error. Otherwise, we'll return a suitable error message.

[01:11] Let's apply the same logic to our min length function, and the same for our max length function. Now let's head over back to our register form. Instead of importing validate from validation, we're going to need to import the functions that we've just written, so required min length and max length.

[01:47] Then we can remove the validate function from being passed into our decorator. The way that we hook this up is to pass in an array to the validate prop on each of our fields.

[02:04] For the first name, we want this to be required, same thing for the surname. For the user name, let's have required min length, max length.

[02:22] Let's save and refresh now, and let's test our values. We have the same result as before, so the two separate ways of applying synchronous validation in Redux Form will depend on your own situation and preference.