Home > Enterprise >  How to validate an single/multiple image in Javascript and show error message below the input with p
How to validate an single/multiple image in Javascript and show error message below the input with p

Time:02-28

Actually I have a form where with image input. I want to validate image for three condition like

  1. extension should be png, jpg
  2. size should be less than 2048kb
  3. less than 200px x 200px is consider as dimension

I wrote an function and solve 1 and 2 issue. To solve issue 3 , I use image reader inside onl oad listener and when I clicked it can not prevent submit also if I remove 3, then it works fine ! Is there any solution in JS that solve above issue?

Here is a slide of my code in below.

function isImageValid(idName) {

    var fileUpload = document.getElementById(idName);
     var fileName = document.getElementById(idName).value;


    if (typeof (fileUpload.files) != "undefined") {
        for (var i=0; i<fileUpload.files.length;i  )
   {
    //    console.log(fileUpload.files[i]);
        var valid_dimension = 0;

       var reader = new FileReader();

        //Read the contents of Image File.
        reader.readAsDataURL(fileUpload.files[0]);
        reader.onload = function (e) {

        //Initiate the JavaScript Image object.
        var image = new Image();

        //Set the Base64 string return from FileReader as source.
        image.src = e.target.result;

        //Validate the File Height and Width.
        image.onload = function () {
            var height = this.height;
            var width = this.width;

            if (height>200||width>200) {

           valid_dimension =1;
            // alert("Height and Width must not exceed 200px.");
             return false;
            }
        //    alert("Uploaded image has valid Height and Width.");
             return true;
        };


        };
         var size = parseFloat(fileUpload.files[0].size / 1024).toFixed(2);
         var extension = fileName.split('.').pop();

       if( valid_dimension ==1||size>2048||(extension!='jpg'&&extension!='JPG'&&extension!='JPEG'&&extension!='jpeg'&&extension!='png'&&extension!='PNG'))
       return false;
       else
       return true;
   }



    } else {
       return false;
    }
}

And,

    const form = document.getElementById('employee_form');
  form.addEventListener('submit', (e)=>{

var is_avatar_img_valid = isImageValid('avatar');
if(is_avatar_img_valid==false){

         e.preventDefault();
         document.getElementById("avatar").style.borderColor = "red";
         document.getElementById('avatar_validator_message').innerHTML = 'Invalid image';
       }
       else{
        document.getElementById("avatar").style.borderColor = "black";
        document.getElementById('avatar_validator_message').innerHTML = '';
      }
}

CodePudding user response:

Inside the form eventlister you need to use

e.preventDefault()

The full code looks like this

const form = document.getElementById('employee_form');
form.addEventListener('submit', (e) => {
    e.preventDefault()

    var is_avatar_img_valid = isImageValid('avatar');
    if (is_avatar_img_valid == false) {

        e.preventDefault();
        document.getElementById("avatar").style.borderColor = "red";
        document.getElementById('avatar_validator_message').innerHTML = 'Invalid image';
    }
    else {
        document.getElementById("avatar").style.borderColor = "black";
        document.getElementById('avatar_validator_message').innerHTML = '';
    }
});

CodePudding user response:

The problem is reader.onload and image.onload functions are async in nature. So your form submits before these onl oad methods execute. To solve this you need to follow the below steps

  1. Prevent default in submit event handler
  2. Pass callbacks for valid and invalid image to the isImageValid function
  3. Manually submit the form if image is valid

Below is the code. Please mark the answer as accepted, if it helps

function isImageValid(idName, onValidCallback, onInvalidCallback) {
    var fileUpload = document.getElementById(idName);
    var fileName = document.getElementById(idName).value;

    if (typeof (fileUpload.files) != "undefined") {
        for (var i = 0; i < fileUpload.files.length; i  ) {
            //    console.log(fileUpload.files[i]);
            //--------------------
            const allowedExtension = ['jpg', 'JPG', 'JPEG', 'jpeg', 'png', 'PNG'];
            const maxAllowedSize = 2048;
            const maxAllowedHeight = 200;
            const maxAllowedWidth = 200;

            const size = parseFloat(fileUpload.files[i].size / 1024).toFixed(2);
            const extension = fileName.split('.').pop();

            console.log({ size, extension });
            //Check for valid extension and size limit
            if (allowedExtension.some(ext => ext === extension) && size <= maxAllowedSize) {
                //Extension and size are valid
                // Now check for valid dimensions

                const reader = new FileReader();
                reader.readAsDataURL(fileUpload.files[i]);

                reader.onload = function (e) {
                    //Initiate the JavaScript Image object.
                    var image = new Image();

                    //Set the Base64 string return from FileReader as source.
                    image.src = e.target.result;

                    //Validate the File Height and Width.
                    image.onload = function () {
                        const height = this.height;
                        const width = this.width;

                        console.log({ height, width });
                        if (height > maxAllowedHeight || width > maxAllowedWidth) {
                            // alert("Height and Width must not exceed 200px.");

                            //File does not meet the dimensions guidline
                            if (onInvalidCallback)
                                onInvalidCallback();
                            return false;
                        }

                        //    alert("Uploaded image has valid Height and Width.");

                        //Everything is fine, form canbe submitted now
                        if (onValidCallback)
                            onValidCallback();
                    };
                };
            }
            break;
        }
    }
    else {
        // There are no files selected
        if (onInvalidCallback)
            onInvalidCallback();
    }
}

const form = document.getElementById('employee_form');
form.addEventListener('submit', (e) => {
    e.preventDefault();
    isImageValid('avatar', () => {
        alert('going to submit');
        document.getElementById("avatar").style.borderColor = "black";
        document.getElementById('avatar_validator_message').innerHTML = '';

        //Manually submit the form
        form.submit();
    },
        () => {
            alert('stop submit');
            document.getElementById("avatar").style.borderColor = "red";
            document.getElementById('avatar_validator_message').innerHTML = 'Invalid image';
        }
    );
    return false;    
});

  • Related