export interface FileValidationOptions { allowedExtensions?: string[] allowedMimeTypes?: string[] } export interface FileValidationResult { isValid: boolean error?: string } export interface FileSizeValidationResult { isValid: boolean error?: string } /** * Hjälpfunktion för att validera filtyper * @param options - Alternativ för validering (tillåtna filändelser och MIME-typer) * @returns Funktion för att validera en fil */ export function useFileValidation(options: FileValidationOptions = {}) { const defaultOptions: Required = { allowedExtensions: [], allowedMimeTypes: [] } const config = { ...defaultOptions, ...options } const validateFile = (file: File | null | undefined): FileValidationResult => { if (!file) { return { isValid: false, error: 'No file provided' } } const fileName = file.name.toLowerCase() const fileExtension = fileName.substring(fileName.lastIndexOf('.')) const fileMimeType = file.type // Kontrollera filändelse const isValidExtension = config.allowedExtensions.length === 0 || config.allowedExtensions.some((ext) => ext.toLowerCase() === fileExtension) // Kontrollera MIME-typ const isValidMimeType = config.allowedMimeTypes.length === 0 || config.allowedMimeTypes.includes(fileMimeType) // Filen är giltig om antingen extension eller MIME-typ matchar const isValid = isValidExtension || isValidMimeType if (!isValid) { return { isValid: false, error: `File type not allowed. Allowed types: ${config.allowedExtensions.join(', ')}` } } return { isValid: true } } return { validateFile } } /** * Hjälpfunktion för att validera maximal filstorlek * @param maxFileSize - Maximal filstorlek i bytes * @returns Funktion för att validera en fils storlek */ export function useFileSizeValidation(maxFileSize: number) { const validateFileSize = (file: File | null | undefined): FileSizeValidationResult => { if (!file) { return { isValid: false, error: 'No file provided' } } if (file.size > maxFileSize) { const maxSizeMB = (maxFileSize / (1024 * 1024)).toFixed(2) const fileSizeMB = (file.size / (1024 * 1024)).toFixed(2) return { isValid: false, error: `File size (${fileSizeMB} MB) exceeds maximum allowed size of ${maxSizeMB} MB` } } return { isValid: true } } return { validateFileSize } }