I'd like to know how to use jquery validate to validate the dimensions of the image being uploaded. In my case, the image has to be 400px in height and width.
I'd like to know how to use jquery validate to validate the dimensions of the image being uploaded. In my case, the image has to be 400px in height and width.
To do this you need to create a custom validation, here's an example:
function readImage(file, element) {
var reader = new FileReader();
var image = new Image();
reader.readAsDataURL(file);
reader.onload = function (_file) {
image.src = _file.target.result;
image.onload = function() {
$(element).data('height', this.height);
$(element).data('width', this.width);
$(element).data('size', ~~((file.size / 1024) / 1024));
}
}
};
jQuery.validator.addMethod('height', function (value, element, param) {
if ($(element).data('height')) {
return $(element).data('height') == param;
} return this.optional(element) || true;
}, 'A altura deve ser exatamente {0}px');
jQuery.validator.addMethod('width', function (value, element, param) {
if ($(element).data('width')) {
return $(element).data('width') == param;
} return this.optional(element) || true;
}, 'A largura deve ser exatamente {0}px');
jQuery(function ($) {
"use strict";
$('#image').change(function () {
var files = this.files;
if (files && files[0]) {
readImage(files[0], '#image');
}
});
$('#update_profile').validate({
rules: {
image: {
required: true,
width: 400,
height: 400,
}
},
});
});
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<form id="update_profile" method="post" action="">
<input type="file" name="image" id="image" />
<input type="submit" value="Save" />
</form>