Validate Image Content in ReactJS
Today we will show you how to validate image content in ReactJS. When we are working with the image upload functionality then we also need to implement the validation for the image content as well.
Validate image size, extension and type in ReactJS, Validate file upload in React JS, file upload validation in reactjs, Implement validation in file upload, How to validate upload file size and file extension using React JS.
Checkout more articles on ReactJS
Everyone knows about the image validation based on the extension but we also need to implement the validation for the image content in ReactJS.
What is image content validation?
Let’s give you an example to understand it. First, create a text file (.txt
) and then change the extension of the same file from .txt
to .png
. After that when you upload this file then it will pass the extension validation but still, it’s invalid so we need to prevent it to upload on the server.
Way to validate image content in ReactJS
1. Image upload in ReactJS
Let’s begin with the very basic example of the image upload in ReactJS. If you don’t know how to upload an image in ReactJS then go through the link below.
Image upload in ReactJS2. Implement image content validation
Here we will validate the image in two different ways.
- Validate image extension: For that we will match the file name extension.
- Validate image content: For that we have to use
FileReader()
to read the file and it will return the image inbase64
string. So when we load it in image object then it will throw an error if image is invalid.
We covered both validations in the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | constructor(props) { ... ... this.reader = new FileReader(); } ... ... // handle change event of input file and validate it onChangeFile = event => { const imageFile = event.target.files[0]; if (!imageFile) { this.setState({ invalidImage: 'Please select image.' }); return false; } if (!imageFile.name.match(/\.(jpg|jpeg|png|gif)$/)) { this.setState({ invalidImage: 'Please select valid image.' }); return false; } this.reader.onload = (e) => { const img = new Image(); img.onload = () => { this.setState({ selectedFile: imageFile, invalidImage: null }); }; img.onerror = () => { this.setState({ invalidImage: 'Invalid image content.' }); return false; }; img.src = e.target.result; }; this.reader.readAsDataURL(imageFile); } |
Let’s combine all the code together to see how it looks.
Here, We need server support in form of API to upload image to a server. For that we have to create the file upload API in Node.js. Please refer below link if you don’t know about it.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | import React, { Component } from 'react'; import axios from 'axios'; // base url of API const BASE_URL = 'http://localhost:4000/'; class App extends Component { constructor(props) { super(props); this.state = { selectedFile: null, // to store selected file handleResponse: null, // handle the API response imageUrl: null, // to store uploaded image path invalidImage: null // handle the message of the image validation }; this.reader = new FileReader(); } // handle change event of input file and validate it onChangeFile = event => { const imageFile = event.target.files[0]; if (!imageFile) { this.setState({ invalidImage: 'Please select image.' }); return false; } if (!imageFile.name.match(/\.(jpg|jpeg|png|gif)$/)) { this.setState({ invalidImage: 'Please select valid image.' }); return false; } this.reader.onload = (e) => { const img = new Image(); img.onload = () => { this.setState({ selectedFile: imageFile, invalidImage: null }); }; img.onerror = () => { this.setState({ invalidImage: 'Invalid image content.' }); return false; }; debugger img.src = e.target.result; }; this.reader.readAsDataURL(imageFile); } // handle click event of the upload button handleUpload = () => { const { selectedFile } = this.state; if (!selectedFile) { this.setState({ handleResponse: { isSuccess: false, message: "Please select image to upload." } }); return false; } const formData = new FormData(); formData.append('dataFile', selectedFile, selectedFile.name); axios.post(BASE_URL + 'uploadfile', formData).then(response => { this.setState({ handleResponse: { isSuccess: response.status === 200, message: response.data.message }, imageUrl: BASE_URL + response.data.file.path }); }).catch(err => { alert(err.message); }); } render() { const { handleResponse, imageUrl, invalidImage } = this.state; return ( <div className="App" > <h4>Validate Image Content in ReactJS - Clue Mediator</h4> <p className="title">Select Image:</p> <div style={{ marginBottom: 10 }}> <input type="file" onChange={this.onChangeFile} /> </div> {invalidImage && <p className="error">{invalidImage}</p>} <input type="button" value="Upload" onClick={this.handleUpload} /> {handleResponse && <p className={handleResponse.isSuccess ? "success" : "error"}>{handleResponse.message}</p>} <p className="title" style={{ marginTop: 30 }}>Uploaded Image:</p> {imageUrl && <img src={imageUrl} alt="Uploaded File" height="100" width="100" />} </div> ); } } export default App; |
3. Output
Thank you for the reading. Happy Coding!