A factory function that we can use to create custom file validators.

Our custom validator extension needs to return a validateEntry function and a canValidateEntry function and it defines an options object that extends ValidatorExtensionOptions.

Example

Let’s create a custom age validator extension, it can validate if a file is too old or too new.

import { defineFilePond, createValidatorExtension } from 'filepond';
import { locale } from 'filepond/locales/en-gb.js';
import { ConsoleView } from 'filepond/extensions/console-view.js';

// Create the extension
const FileAgeValidator = createValidatorExtension(
    // A unique name for our extension
    'FileAgeValidator',

    // Default options
    {
        // min age in milliseconds
        minAge: 0,

        // max age in milliseconds
        maxAge: Infinity,
    },

    // Validation functions
    ({ props, didSetProps }) => {
        function validateEntry(entry) {
            const { lastModified } = entry.file;
            const { minAge, maxAge } = props;

            // file age
            const age = Date.now() - lastModified;

            // too new?
            if (age < minAge) {
                return {
                    code: 'VALIDATION_FILE_AGE_UNDERFLOW',
                    values: {
                        minAge,
                    },
                };
            }

            // too old?
            if (age > maxAge) {
                return {
                    code: 'VALIDATION_FILE_AGE_OVERFLOW',
                    values: {
                        maxAge,
                    },
                };
            }

            // all good!
            return null;
        }

        function canValidateEntry(entry) {
            // we can only test files
            if (!(entry.file instanceof File)) {
                return false;
            }

            // we can validate this entry
            return true;
        }

        // return the functions to the `createValidatorExtension` factory
        return {
            validateEntry,
            canValidateEntry,
        };
    }
);

// Use the extension
defineFilePond({
    // Add our custom validation labels to the locale
    locale: {
        ...locale,

        // add our custom validation labels
        validationFileAgeUnderflow:
            'This file is too new. Minimum file age is {{minAge}}ms.',
        validationFileAgeOverflow:
            'This file is too old. Maximum file age is {{maxAge}}ms.',
    },

    // Add our custom FileAgeValidator extension
    extensions: [
        [
            FileAgeValidator,
            {
                // set max file age to 1000 milliseconds
                maxAge: 1000,
            },
        ],

        // Add the ConsoleView extension for debugging purposes
        ConsoleView,
    ],
});