Validate single/multiple image field using Javascript

0

Image validation code is one of the most commonly used snippet. I have used this snippet on almost every project I worked on. So this time I thought to share this code with all of you. You can use this snippet to validate single/ multiple image field using JavaScript on any project you like.

Steps to validate image field using JavaScript

It’s a two steps process,

  1. Add input field (file type) in your php, html, asp file.
  2. Write JavaScript code to validate that image field. and bind the validation to an event (I have used onchange event to trigger the validation code).

Note: I have used FormData API to validate, it supports on all modern browser but not on old browser. You can see the latest wiki info here.

Validate single image field using JavaScript

Add image field code in your html, php,  asp file.

Once you are done with the above, create a JavaScript function validateImage() you can name this function according to your preference. When validating you should check the image type and image size to keep up a limit. In my code I will check image of jpeg, jpg, png, bmp, and gif types only. Also the maximum upload image size is 1MB.

Additionally you can also put this attribute ‘accept=”image/*”‘ in the input field, so user can only see file of image type file when uploading the image from their system.

Validate multiple image field using JavaScript

I would like to recommend that first of all you try validate single image and check if that is working perfectly then move on with this multiple image field validation.

In this section you can validate multiple image field, first of all create 3 image fields ( you can create many) and assign each one of them with a unique ID, then bind them on onchange event with a JavaScript function and pass the unique ID as a parameter in the function.

Customize the javascript validation function that we wrote before. Everything will be same except the ID will be dynamic now and will be passed as a parameter.

If you know any better technique to validate the image fields please do share with us.

Share.
 

About Author

Entrepreneur & Dreamer

I am a passionate Software Professional, love to learn and share my knowledge with others.

Software is the hardware of my life.

Leave A Reply

CommentLuv badge

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.