How to validate an image in redux-form? š¼
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! š
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: šØ
- Create a
react
app. - Add
redux
andredux-form
as dependencies - Connect
redux
andreact
- 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!