使用 jQuery 插件验证图像尺寸

use*_*120 6 javascript jquery jquery-validate

我有一个表单,其中在 jQuery 的验证插件中进行验证。我的表单包含两个元素,一个 input type=file 和一个提交按钮。用户将选择一个图像,如果该图像小于 500 像素,则不会被接受,并应显示错误消息。我为此创建了一个称为宽度的新方法,但由于某种原因它不起作用。当我尝试提交小于 500 像素的图像时,不会显示错误消息。这是我的jsfiddle

HTML

<form class="some_form" enctype="multipart/form-data" method="post" action="">
  <input type="file" name="photo" id="photoInput" />
  <input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)

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"
    },
  }

});
Run Code Online (Sandbox Code Playgroud)

Joh*_*n S 7

您可以将图像文件加载到<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>
Run Code Online (Sandbox Code Playgroud)

接下来,定义一个自定义 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's width must be greater than " + minWidth + "px")
      : "Selected file is not an image.";
});
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 如您所见,该方法期望它可以通过调用.data('imageWidth')文件输入元素来获取图像宽度。我们将在下面显示的代码中设置该值。
  2. 此外,该方法假定当.data('imageWidth')返回时undefined,所选文件不是图像。

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

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

最后,为创建<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);
  }
});
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 加载图像时,其宽度将作为.data('imageWidth')值放置在文件输入元素上。
  2. 在加载图像时,提交按钮被禁用,因此用户无法提交表单。
  3. 加载图像后立即执行验证。也就是说,用户不必单击提交按钮来显示错误消息。这是通过调用 来完成的validator.element()
  4. 在将<img>元素添加到 DOM 之前,您无法获得元素的宽度。它也必须是可见的,但上面的代码显示了如何在需要时立即隐藏它。

提琴手


参考: