How to validate an image in redux-form? šŸ–¼

Pourya Dashtegoli Pour
Strands Tech Corner
3 min readFeb 7, 2019

A couple of weeks ago, we came across an issue when validating images using redux-form. Not only did we have to validate the format and size of the image file but also its width and height. Looking around the web there was no clear, well-explained solution to the problem, soā€¦ hereā€™s one! šŸ“

Mad Alchemist by Jona Dinges

Solution:

In this tutorial, we will learn how to validate both image format and the file size, width and height of an image. šŸ“

Limitations:

The main limitation we faced was as a result of all the elements stored in a file object, including: lastModified, lastModifiedDate, name, size, type, webkitRelativePath and of course __proto__. As you see, these are not enough for us to validate the width and height of an image.

Prerequisites: šŸŽØ

  1. Create a react app.
  2. Add redux and redux-form as dependencies
  3. Connect redux and react
  4. Add semantic-ui-react to access its nice UI components [this step is optional].

Step 1:

First, letā€™s import all the necessary stuff at the top, such as React, PropTypes, Field, reduxForm, Button and Form. As mentioned before, using Semantic UI is totally optional. In our Field weā€™ll have to pass our own component so that we can catch onChange events in the code below- it is written as this.renderFileInput and is explained later in this post.

Next, add the prop types and default props. And then a simple tiny form, a field and a submit button, as in the code below:

Step 2:

Letā€™s add those validation methods. First the easiest (file size); to do that just get the input file object and retrieve size from it. Then you can convert the size to kilobytes, megabytes or anything you want! Add your validation criteria and send an error message.

Next, file format; this oneā€™s really simple too; to do that just retrieve type from file object and validate it. šŸ˜Š #lazywriting

Next, width and height. To achieve this, weā€™ll have to catch any onChange event from our redux field, construct a URL object (letā€™s call it imageObject) with our input file object (letā€™s call this imageFile), check image width and height from the URL object and finally store width and height in our input file object.

Field Component:

Change Handler:

Width and Height Validations:

What happens now, once an image is selected by our input field, an onChange event is invoked, which in result will create a URL object from our image file, retrieve its width and height, sort them in the imageFile object and call the onChange once again but this time our imageFile object has width and height set in them! Next, the validation methods will be called by redux form validation just like a normal validation method.

Code:

You can check the complete code below:

Hope someone out there finds this helpful.

Cheers!

--

--