<img>, .
HTML, <img>:
<form class="some_form" enctype="multipart/form-data" method="post" action="">
<input type="file" name="photo" id="photoInput" />
<input type="submit">
</form>
<div id="imgContainer"></div>
Validator:
$.validator.addMethod('minImageWidth', function(value, element, minWidth) {
return ($(element).data('imageWidth') || 0) > minWidth;
}, function(minWidth, element) {
var imageWidth = $(element).data('imageWidth');
return (imageWidth)
? ("Your image width must be greater than " + minWidth + "px")
: "Selected file is not an image.";
});
:
- , , ,
.data('imageWidth') . , . - , ,
.data('imageWidth') undefined, .
minImageWidth :
var validator = $('.some_form').validate({
rules: {
photo: {
required: true,
minImageWidth: 500
}
},
messages: {
photo: {
required: "You must insert an image"
},
}
});
, , <img> . .data('imageWidth') .
var $submitBtn = $('.some_form').find('input:submit'),
$photoInput = $('#photoInput'),
$imgContainer = $('#imgContainer');
$('#photoInput').change(function() {
$photoInput.removeData('imageWidth');
$imgContainer.hide().empty();
var file = this.files[0];
if (file.type.match(/image\/.*/)) {
$submitBtn.attr('disabled', true);
var reader = new FileReader();
reader.onload = function() {
var $img = $('<img />').attr({ src: reader.result });
$img.on('load', function() {
$imgContainer.append($img).show();
var imageWidth = $img.width();
$photoInput.data('imageWidth', imageWidth);
if (imageWidth < 500) {
$imgContainer.hide();
} else {
$img.css({ width: '400px', height: '200px' });
}
$submitBtn.attr('disabled', false);
validator.element($photoInput);
});
}
reader.readAsDataURL(file);
} else {
validator.element($photoInput);
}
});
:
jsfiddle
: