JavaScript validation on image field

Here we are implementing Validation of image extension before uploading file Using JavaScript. Goal of this tutorial to first validate the upload file is an image and if it is an image I will upload it otherwise fail to upload and show the error.

HTML code for image uploading

<input type="file" name="imagefile" id="imagefile" onchange="return ValidateFileUpload()" />

JavaScript validation code for image uploading

<SCRIPT type="text/javascript">
function ValidateFileUpload(){
    var fuData = document.getElementById('imagefile');
    var FileUploadPath = fuData.value;
    //To check if user upload any file
    if (FileUploadPath == '') {
        alert("Please upload an image");
    }
    else {
        var Extension = FileUploadPath.substring(
        FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
        //The file uploaded is an image
        if (Extension == "gif" || Extension == "png" || Extension == "bmp" || Extension == "jpeg" || Extension == "jpg")
        {
            // To Display
            if (fuData.files && fuData.files[0])
            {
                var reader = new FileReader();
                reader.onload = function(e) {
                    $('#blah').attr('src', e.target.result);
                }
                reader.readAsDataURL(fuData.files[0]);
            }
        }
        //The file upload is NOT an image
        else {
            alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
        }
    }
}    
</SCRIPT>
Mukesh Jakhar - PHP Web Developer
Mukesh Jakhar

This is Mukesh Jakhar. I’m a professional web developer with 3+ years experience. I am always ready for freelance work and i am writing blogs in my free time. I love to learn new technologies and share with others.

I founded PHPKIDA in September 2015. The focus of this website to provide web development tutorials of PHP, WordPress, CodeIgniter, Jquery, MySQL, HMTL, CSS etc and sharing solution to problems which i already solved.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.