or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-widget.mdcross-browser-support.mdfile-processing.mdindex.mduser-interface.mdvalidation.md
tile.json

validation.mddocs/

Validation

The validation plugin provides comprehensive file validation capabilities including file type checking, size limits, upload count restrictions, and customizable error messages with internationalization support.

Capabilities

Validation Configuration Options

Options for configuring file validation rules and constraints.

interface ValidationOptions {
    /** Allowed file types pattern, default: undefined */
    acceptFileTypes?: RegExp;
    
    /** Maximum file size in bytes, default: undefined */
    maxFileSize?: number;
    
    /** Minimum file size in bytes, default: undefined */
    minFileSize?: number;
    
    /** Maximum number of files allowed, default: undefined */
    maxNumberOfFiles?: number;
    
    /** Function to get current file count, default: $.noop */
    getNumberOfFiles?: () => number;
}

Internationalization Options

Options for customizing error messages and supporting multiple languages.

interface InternationalizationOptions {
    /** Error/info messages for translation */
    messages?: ValidationMessages;
    
    /** Translation function for message interpolation */
    i18n?: (message: string, context?: object) => string;
}

interface ValidationMessages {
    /** File type not allowed message */
    acceptFileTypes?: string;
    
    /** File too large message */
    maxFileSize?: string;
    
    /** File too small message */
    minFileSize?: string;
    
    /** Too many files message */
    maxNumberOfFiles?: string;
    
    /** Upload cancelled message */
    uploadedBytes?: string;
    
    /** Empty result message */
    emptyResult?: string;
}

Default Validation Messages

Default error messages used by the validation system.

const defaultMessages = {
    acceptFileTypes: 'File type not allowed.',
    maxFileSize: 'File is too large.',
    minFileSize: 'File is too small.',
    maxNumberOfFiles: 'Maximum number of files exceeded.',
    uploadedBytes: 'Uploaded bytes exceed file size.',
    emptyResult: 'Empty file upload result.'
};

Validation Processing Action

The validate action that can be added to the processing queue.

/**
 * Validate file against size, type, and count constraints
 * This action is automatically configured based on validation options
 */
interface ValidateAction {
    action: 'validate';
}

Validation Error Handling

How validation errors are reported and handled in the data object.

interface ValidationError {
    /** Error message */
    message: string;
    
    /** Error type/code */
    error: string;
    
    /** File that caused the error */
    file: File;
    
    /** File index in the files array */
    index: number;
}

interface ValidatedData extends FileUploadData {
    /** Array of validation errors */
    errors?: ValidationError[];
    
    /** Whether validation passed */
    valid?: boolean;
}

Usage Examples:

// Basic file type and size validation
$('#fileupload').fileupload({
    url: '/upload',
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 5000000, // 5 MB
    minFileSize: 1000,    // 1 KB
    maxNumberOfFiles: 10,
    
    // Add validate action to processing queue
    processQueue: [
        { action: 'validate' }
    ],
    
    // Handle validation failures
    processfail: function (e, data) {
        if (data.errors) {
            data.errors.forEach(function(error) {
                console.error('Validation error:', error.message);
                console.error('File:', error.file.name);
            });
        }
    }
});

// Custom validation messages
$('#fileupload').fileupload({
    url: '/upload',
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 2000000, // 2 MB
    
    messages: {
        acceptFileTypes: 'Only image files (GIF, JPEG, PNG) are allowed.',
        maxFileSize: 'File size must not exceed 2 MB.',
        minFileSize: 'File must be at least 1 KB in size.',
        maxNumberOfFiles: 'You can upload a maximum of {maxNumberOfFiles} files.'
    },
    
    processQueue: [{ action: 'validate' }]
});

// Internationalization with custom i18n function
$('#fileupload').fileupload({
    url: '/upload',
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 5000000,
    maxNumberOfFiles: 5,
    
    messages: {
        acceptFileTypes: 'error.acceptFileTypes',
        maxFileSize: 'error.maxFileSize',
        maxNumberOfFiles: 'error.maxNumberOfFiles'
    },
    
    // Custom internationalization function
    i18n: function(message, context) {
        // Lookup message in translation dictionary
        var translations = {
            'error.acceptFileTypes': 'Only image files are allowed.',
            'error.maxFileSize': 'File is too large (max {maxFileSize}).',
            'error.maxNumberOfFiles': 'Too many files (max {maxNumberOfFiles}).'
        };
        
        var translated = translations[message] || message;
        
        // Replace placeholders with context values
        if (context) {
            Object.keys(context).forEach(function(key) {
                var placeholder = '{' + key + '}';
                translated = translated.replace(placeholder, context[key]);
            });
        }
        
        return translated;
    },
    
    processQueue: [{ action: 'validate' }]
});

// Dynamic file count validation
var currentFileCount = 0;

$('#fileupload').fileupload({
    url: '/upload',
    maxNumberOfFiles: 10,
    
    // Custom function to get current file count
    getNumberOfFiles: function() {
        return currentFileCount;
    },
    
    processQueue: [{ action: 'validate' }],
    
    // Update counter on successful upload
    done: function(e, data) {
        currentFileCount += data.files.length;
    },
    
    // Handle file removal
    destroyed: function(e, data) {
        currentFileCount -= 1;
    }
});

// Comprehensive validation with all options
$('#fileupload').fileupload({
    url: '/upload',
    
    // File type validation (images only)
    acceptFileTypes: /^image\/(gif|jpeg|png|webp)$/i,
    
    // Size constraints (100KB - 10MB)
    minFileSize: 100000,   // 100 KB
    maxFileSize: 10000000, // 10 MB
    
    // Upload limit
    maxNumberOfFiles: 20,
    
    // Custom validation messages
    messages: {
        acceptFileTypes: 'Please select a valid image file (GIF, JPEG, PNG, WebP).',
        maxFileSize: 'The selected file is too large. Please choose a file smaller than 10 MB.',
        minFileSize: 'The selected file is too small. Please choose a file larger than 100 KB.',
        maxNumberOfFiles: 'You have reached the maximum limit of 20 files.',
        emptyResult: 'The upload returned an empty result.'
    },
    
    processQueue: [{ action: 'validate' }],
    
    // Detailed error handling
    processfail: function(e, data) {
        var errors = data.errors || [];
        errors.forEach(function(error, index) {
            var errorMessage = 'File "' + error.file.name + '": ' + error.message;
            $('#error-messages').append('<div class="alert alert-danger">' + errorMessage + '</div>');
        });
    },
    
    // Clear errors on new selection
    change: function(e, data) {
        $('#error-messages').empty();
    }
});

// Server-side validation integration
$('#fileupload').fileupload({
    url: '/upload',
    
    // Client-side pre-validation
    processQueue: [{ action: 'validate' }],
    
    // Handle server-side validation errors
    fail: function(e, data) {
        if (data.jqXHR.status === 400) {
            var serverErrors = JSON.parse(data.jqXHR.responseText);
            serverErrors.forEach(function(error) {
                $('#error-messages').append('<div class="alert alert-danger">' + error.message + '</div>');
            });
        }
    }
});