Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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

    Rory SmithRory Smith

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.