Validate dimensions (Height and Width) of Image before Upload using HTML5 and jQuery

, ,

In this article I will explain how to get and then validate (check) dimensions (Height and Width) of Image file before upload using HTML5 and jQuery.

The following HTML markup consists of an HTML FileUpload and a Button. When the button is clicked, a jQuery click event handler is executed.


<input type="file" id="fileUpload" />
<input id="upload" type="button" value="Upload" />


<script type="text/javascript" src=""></script>
<script type="text/javascript">
$(function () {
    $("#upload").bind("click", function () {
        //Get reference of FileUpload.
        var fileUpload = $("#fileUpload")[0];
        //Check whether the file is valid Image.
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {
            //Check whether HTML5 is supported.
            if (typeof (fileUpload.files) != "undefined") {
                //Initiate the FileReader object.
                var reader = new FileReader();
                //Read the contents of Image File.
                reader.onload = function (e) {
                    //Initiate the JavaScript Image object.
                    var image = new Image();
                    //Set the Base64 string return from FileReader as source.
                    image.src =;
                    image.onload = function () {
                        //Determine the Height and Width.
                        var height = this.height;
                        var width = this.width;
                        if (height > 200 || width > 200) {
                            alert("Max allowed with and height is 200px");
                            return false;
                        alert("Uploaded image has valid Height and Width.");
                        return true;
            } else {
                alert("This browser does not support HTML5.");
                return false;
        } else {
            alert("Please select a valid Image file.");
            return false;

Inside the jQuery click event handler, few checks are performed such as whether the File is a valid Image file and the browser supports HTML5 File API.

Then using the HTML5 FileReader API, the Image File is read as Base64 string and then is assigned as source to a JavaScript Image object.

Finally inside the onload event handler of the JavaScript Image object, the dimensions i.e. Height and Width of the selected Image file is determined.

Related Post

Latest Post

Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.