0

please help to find out issue with my jquery validation. I am using jQuery Validation plugin for validate my form. I have added a custom rule for check dimension of an image(trying to upload image). Here is code for custom method

$.validator.addMethod('checkDim', function (value, element, param) {     
    var image = new Image();
    var file = element.files[0];
    var _URL = window.URL || window.webkitURL;
    image.src = _URL.createObjectURL(file);
    image.onload = function () {
        console.log("The image width is " + this.width + " and image height is " + this.height);
        if(this.width == param[0] && this.height == param[1]){ 
            return true;
        }
        else{            
            return false;
        }
    };  

}, 'Image dimension must be as specified');

I have added a rule like below

image: {required: true, accept: "image/*", checkDim: [1366,311]}

function is called correctly as i can see message in console and also dimension is also calculate correctly but this function always return invalid.

Please help me to figure out what i am doing wrong.

Sparky
  • 98,165
  • 25
  • 199
  • 285
Karan
  • 2,102
  • 2
  • 22
  • 31

1 Answers1

0

Your element parameter will gives attribute related to your element i.e. your image.You don;t need onload event or need to create Image Object.

$.validator.addMethod('checkDim', function(value, element, param) {
        var width = $(element).width();
        var height = $(element).height();
        console.log("The image width is " + width + " and image height is " + height);
        if (width == param[0] && height == param[1]) {
            return true;
        } else {
            return false;
        }
    }, 'Image dimension must be as specified');
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53