使用jQuery插件验证图像尺寸 [英] Validating image dimensions using jQuery plugin

查看:92
本文介绍了使用jQuery插件验证图像尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中在jQuery的验证插件中进行验证.我的表单包含两个元素,一个输入类型=文件和一个提交按钮.用户将选择一个图像,如果该图像小于500像素,则该图像将不被接受,并应显示一条错误消息.我为此创建了一个新的方法width,但是由于某种原因它无法正常工作.当我尝试提交小于500px的图像时,未显示错误消息.这是我的 jsfiddle .

I have a form where validation occurs in jQuery's validation plugin. My form contains two elements, an input type=file and a submit button. The user will select an image, and if that image is less than 500px, it won't be accepted and an error message should be shown. I have made a new method for this called width, but it's not working for some reason. The error message is not shown when I try to submit an image less than 500px. Here's my jsfiddle.

HTML

<form class="some_form" enctype="multipart/form-data" method="post" action="">
  <input type="file" name="photo" id="photoInput" />
  <input type="submit">
</form>

jQuery

$.validator.addMethod('width', function(value, element) {
  if ($(element).data('width')) {
    return $(element).data('width') >= 500;
  }

  return true;
}, 'Image needs to be wider than 500px');

$(".some_form").validate({
  rules: {
    photo: {
      required: true,
      width: 500
    }

  },

  messages: {
    photo: {
      required: "You must insert an image",
      width: "Your image's width must be greater than 500px"
    },
  }

});

推荐答案

您可以将图像文件加载到< img> 元素中,然后获取该元素的宽度.

You can load the image file into an <img> element, and then get the width of that element.

首先将一个容器元素添加到HTML中,以容纳< img> 元素:

First add a container element to your HTML to hold the <img> element:

<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方法:


Next, define a custom Validator method:

$.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's width must be greater than " + minWidth + "px")
      : "Selected file is not an image.";
});

注意:

  1. 如您所见,该方法期望它可以通过在文件输入元素上调用 .data('imageWidth')来获得图像宽度.我们将在下面显示的代码中设置该值.
  2. 此外,该方法假定 .data('imageWidth')返回 undefined 时,所选文件不是图像.
  1. As you can see, the method expects that it can get the image width by calling .data('imageWidth') on the file input element. We will be setting that value in code shown below.
  2. Also, the method assumes that when .data('imageWidth') returns undefined, the selected file is not an image.


您现在可以像这样使用 minImageWidth 方法:

var validator = $('.some_form').validate({
  rules: {
    photo: {
      required: true,
      minImageWidth: 500
    }
  },
  messages: {
    photo: {
      required: "You must insert an image"
    },
  }
});


最后,为创建< img> 元素的文件输入添加一个更改事件处理程序,并将其添加到容器中.还将在文件输入元素上设置 .data('imageWidth')值.


Finally, add a change-event handler for the file input that creates the <img> element and adds it to the container. It will also set the .data('imageWidth') value on the file input element.

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);
  }
});

注意:

  1. 加载图像时,其宽度作为 .data('imageWidth')值放置在文件输入元素上.
  2. 正在加载图像时,提交"按钮被禁用,因此用户无法提交表单.
  3. 加载图像后立即执行验证.也就是说,用户不必单击提交按钮即可显示错误消息.这是通过调用 validator.element() 来完成的.
  4. 在将< img> 元素添加到DOM之前,无法获得它的宽度.它也必须是可见的,但是上面的代码显示了如何在需要时立即将其隐藏.
  1. When the image is loaded, its width is placed as a .data('imageWidth') value on the file input element.
  2. While the image is loading, the submit button is disabled so the user cannot submit the form.
  3. The validation is performed immediately after the image is loaded. That is, the user does not have to click the submit button in order to for the error message to show up. This is accomplished by the call to validator.element().
  4. You cannot get the width of the <img> element until it is added to the DOM. It must also be visible, but the code above shows how it can be hidden right after if desired.

jsfiddle

jsfiddle

参考文献:

这篇关于使用jQuery插件验证图像尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆