npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

z-file-validator

v1.0.1

Published

Validating file inputs with the File Api.

Downloads

13

Readme

z-file-validator

Build Status npm version

This module was written to handle client-side file input validation, using the File API.

Note: the plugin itself doesn't check for File API support, so the examples will assume that you have something under your belt to handle that. (Like Modernizr.)

Also: this module was written with jQuery in mind. This dependency will most likely be dropped in the future since hardly anything is used from jQuery's functionality.

Since this is a CommonJS module, it must be used alongside with Browserify, or something similar, like WebPacker.

Example, explanation

<!--
    For convenience, sizes can be given as byte integers, or as numbers suffixed
    with one of the following: "Mb", "M", "Kb", "K".
    (Separating the numbers and the suffixes is also allowed, so "1024 K" will
    work just fine.)
    After the module loads the configuration, these will automatically be
    converted to byte integers. (In the example below, "5M" will be converted
    to 5242880)
-->
<!--
    Providing the configuration through a data-* attribute is optional.
    (Explained later in detail.)
-->
<input type="file" id="input" data-configuration='{
    "collective": {
        "size": {
            "min": "1M",
            "max": "20M"
        },
        "count": {
            "min": 1,
            "max": 3
        }
    },
    "size": {
        "min": "1024K",
        "max": "4M"
    }
}' accept="image/*" multiple>

<!--
    Exmplanation for the configuration options:
        - collective: These validations are running considering all the
            selected files.
        - "size" and "accept": These validations run for each selected file
            individually.
        - the "accept" attribute: this could also be provided by the JSON
            configuration, but as an attribute, most browsers will render the
            browsing window so that the selectable files are already filtered.
            Still, it can be used for testing purposes.
-->
var FileValidator = require('z-file-validator');

// Suppose we have Modernizr
if (Modernizr.filereader) {
    // Saving the jQuery object for later use.
    var $input = $('#input');

    // Initializing a FileValidator for the input
    var validator = new FileValidator($input, 'configuration');
    // Where
    // $input          - The DOM input element selected by jQuery.
    // 'configuration' - The data- attribute's name. Now it expects a
    //                   `data-configuration` attribute to contain a valid
    //                   JSON configuration.
    //                   This could also be an object instead, in which case
    //                   there's no need for the data-* attribute.

    // By default, if the `validator.validate()` returns an error, the validator
    // also resets the file input. If you want to keep the selected value
    // regardless of the validation result, then just use the following:
    // `validator.setInputResetOnError(false);`
    // before running the validation.

    // Validate the input on change
    $input.on('change', function() {
        var validationResponse = validator.validate();

        // If you need the loaded configuration to have more sensible error
        // messages, you can just use the following:
        var usedConfig = validator.getConfig();

        if (validationResponse === true) {
            // No problems were detected :thumbsup:
        } else {
            // An error occured, which can be a collective error, or a specific
            // problem with one - or some - of the files.
            if (validator.hasCollectiveErrors() === true) {
                // In this case, `validationResponse` is an array of error code
                // strings.
                // Ex: `["collective.big_filesize", "collective.too_much_file"]`
            } else {
                // In this case, `validationResponse` is an array of arrays,
                // where each contains 2 elements: an array of error codes,
                // and the file data which was fetched from the FileApi.
                // Ex:
                // `[
                //     [
                //         ["big_filesize"],
                //         File
                //     ],
                //     [
                //         ["small_filesize", "bad_type"],
                //         File
                //     ]
                // ]`
            }
        }
    });
}

Validation error codes

Collective

  • "collective.big_filesize"
  • "collective.small_filesize"
  • "collective.too_few_file"
  • "collective.too_much_file"

Individual

  • "big_filesize"
  • "small_filesize"
  • "bad_file_type"

Advanced usage

Most of the FileValidator methods can be used individually, if needed.

For example: with the validateFile method, it's possible to validate only a specific File:

var FileValidator = require('z-file-validator');

var validationResponse = FileValidator.prototype.validateFile(
    $('#input')[0].files[1], // Validating only the second selected file
    {size: {max: '5M'}} // It should be no bigger than 5M
);

console.log(validationResponse);
// -> ["big_filesize"] or
// -> true

License

MIT