-1

Referenece: https://github.com/pes10k/jquery.validate.file/blob/master/jquery.validate.file.js

$("#upload_form").validate({
                rules: {
                    example_file: {
                        fileType: {
                            types: ["pdf", "jpeg", "jpg"]
                        },
                    maxFileSize: {
                        "unit": "KB",
                        "size": 100
                    }
                }
            });

Now how to uses these rules via data-rule attributes? I have tried like data-rule-fileTye-types="['pdf', 'jpeg', 'jpg']" but it is not validating. Please help me

2
  • Welcome to Stack Overflow. This appears to be 12 years old and I see syntax errors in the Example and encounter Errors in my testing of the example. You might want to consider using a more modern plug-in for form validation. IF you insist on using this script, please provide a minimal reproducible example. Commented Jul 14, 2024 at 18:04
  • You have a typo in data-rule-fileTye... note "Tye" instead of "Type". Commented Jul 15, 2024 at 21:38

1 Answer 1

0

As this is a Plug-In to a library, you need to load the library first. Here is an example.

(function($) {
  "use strict";

  // This set of validators requires the File API, so if we'ere in a browser
  // that isn't sufficiently "HTML5"-y, don't even bother creating them.  It'll
  // do no good, so we just automatically pass those tests.
  var is_supported_browser = !!window.File,
    fileSizeToBytes,
    formatter = $.validator.format;

  /**
   * Converts a measure of data size from a given unit to bytes.
   *
   * @param number size
   *   A measure of data size, in the give unit
   * @param string unit
   *   A unit of data.  Valid inputs are "B", "KB", "MB", "GB", "TB"
   *
   * @return number|bool
   *   The number of bytes in the above size/unit combo.  If an
   *   invalid unit is specified, false is returned
   */
  fileSizeToBytes = (function() {

    var units = ["B", "KB", "MB", "GB", "TB"];

    return function(size, unit) {

      var index_of_unit = units.indexOf(unit),
        coverted_size;

      if (index_of_unit === -1) {

        coverted_size = false;

      } else {

        while (index_of_unit > 0) {
          size *= 1024;
          index_of_unit -= 1;
        }

        coverted_size = size;
      }

      return coverted_size;
    };
  }());

  /**
   * Validates that an uploaded file is of a given file type, tested
   * by it's reported mime string.
   *
   * @param obj params
   *   An optional set of configuration parmeters.  Supported options are:
   *    "types" : array (default ["text"])
   *      An array of file types.  This types are loosely checked, so including
   *      "text" in this array of types will cause "text/plain" and "text/css"
   *      to both be excepted.  If the selected file matches any of the strings
   *      in this array, validation passes.
   */
  $.validator.addMethod(
    "fileType",
    function(value, element, params) {

      var files,
        types = params.types || ["text"],
        is_valid = false;

      if (!is_supported_browser || this.optional(element)) {

        is_valid = true;

      } else {

        files = element.files;

        if (files.length < 1) {

          is_valid = false;

        } else {

          $.each(types, function(key, value) {
            is_valid = is_valid || files[0].type.indexOf(value) !== -1;
          });

        }
      }

      return is_valid;
    },
    function(params, element) {
      return formatter(
        "File must be one of the following types: {0}.",
        params.types.join(",")
      );
    }
  );

  /**
   * Validates that a file selected for upload is at least a given
   * file size.
   *
   * @param obj params
   *   An optional set of configuration parameters.  Supported options are:
   *     "unit" : string (default "KB")
   *       The unit of measure of the file size limit is in.  Valid inputs
   *       are "B", "KB", "MB" and "GB"
   *     "size" : number (default 100)
   *        The minimum size of the file, in the above units, that the file
   *        must be, to be accepted as "valid"
   */
  $.validator.addMethod(
    "minFileSize",
    function(value, element, params) {

      var files,
        unit = params.unit || "KB",
        size = params.size || 100,
        min_file_size = fileSizeToBytes(size, unit),
        is_valid = false;

      if (!is_supported_browser || this.optional(element)) {

        is_valid = true;

      } else {

        files = element.files;

        if (files.length < 1) {

          is_valid = false;

        } else {

          is_valid = files[0].size >= min_file_size;

        }
      }

      return is_valid;
    },
    function(params, element) {
      return formatter(
        "File must be at least {0}{1} large.", [params.size || 100, params.unit || "KB"]
      );
    }
  );

  /**
   * Validates that a file selected for upload is no loarger than a given
   * file size.
   *
   * @param obj params
   *   An optional set of configuration parameters.  Supported options are:
   *     "unit" : string (default "KB")
   *       The unit of measure of the file size limit is in.  Valid inputs
   *       are "B", "KB", "MB" and "GB"
   *     "size" : number (default 100)
   *        The maximum size of the file, in the above units, that the file
   *        can be to be accepted as "valid"
   */
  $.validator.addMethod(
    "maxFileSize",
    function(value, element, params) {

      var files,
        unit = params.unit || "KB",
        size = params.size || 100,
        max_file_size = fileSizeToBytes(size, unit),
        is_valid = false;

      if (!is_supported_browser || this.optional(element)) {

        is_valid = true;

      } else {

        files = element.files;

        if (files.length < 1) {

          is_valid = false;

        } else {

          is_valid = files[0].size <= max_file_size;

        }
      }

      return is_valid;
    },
    function(params, element) {
      return formatter(
        "File cannot be larger than {0}{1}.", [params.size || 100, params.unit || "KB"]
      );
    }
  );

}(jQuery));

$(function() {
  $("#upload_form").validate({
    rules: {
      example_file: {
        fileType: {
          types: ["pdf", "jpeg", "jpg"]
        },
        maxFileSize: {
          "unit": "KB",
          "size": 100
        }
      }
    }
  });
});
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>
<form method="post" enctype="multipart/form-data" id="upload_form">
  <input type="file" name="example_file" id="example_file">
  <button type="submit">Upload</button>
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This plugin to validation library actually working great for me. But what I want is just implement via data- attributes just like data-rules-required="true" like this. I dont know how to use it from data- attributes. Is there any way to use it like data-fileType-types="pdf,jpg" Please let me know.
@Learner you would have to review the documentation of the Validate library: jqueryvalidation.org/documentation and jqueryvalidation.org/reference A quick look over it suggests this library does not offer that feature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.