universal-file-validator
v1.0.1
Published
File validation library for images, documents, videos, audio, and archives
Maintainers
Readme
📂 Universal File Validator
A lightweight and flexible file validation library for the browser (TypeScript/JavaScript).
Validate images, PDFs, Word, Excel, PowerPoint, ZIP, video, audio, text, and CSV with customizable rules.
⚠️ This package targets browser environments. It uses
File,FileReader, andImage. To use in Node.js you’ll need DOM/file polyfills.
✨ Features
- Validate file type via MIME/extension + magic numbers where applicable
- Set maximum file size (MB)
- Validate image dimensions (min width & min height)
- Check Office Open XML files (DOCX/XLSX/PPTX) by verifying required entries inside the ZIP
- Validate ZIP by attempting to open it
- Basic video and audio header checks
- Simple text and CSV sanity checks
- Written in TypeScript with type definitions
📦 Installation
npm install universal-file-validator
# or
yarn add universal-file-validator🚀 Quick Start
import { FileValidator, AllowedFileType } from "universal-file-validator";
const validator = new FileValidator({
allowedTypes: [
AllowedFileType.IMAGE,
AllowedFileType.PDF,
AllowedFileType.WORD,
AllowedFileType.EXCEL,
AllowedFileType.POWERPOINT,
AllowedFileType.ZIP,
AllowedFileType.VIDEO,
AllowedFileType.AUDIO,
AllowedFileType.TEXT,
AllowedFileType.CSV
],
maxSizeInMB: 20, // optional (default 50)
minWidth: 200, // optional (default 100, only used for images)
minHeight: 200 // optional (default 100, only used for images)
});
// Example: using an <input type="file">
async function onFileChange(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0];
if (!file) return;
try {
await validator.validate(file);
console.log("✅ File is valid:", file.name);
} catch (err: any) {
console.error("❌ Validation failed:", err.message);
}
}Angular snippet
<input type="file" (change)="onFileChange($event)" />import { Component } from "@angular/core";
import { FileValidator, AllowedFileType } from "universal-file-validator";
@Component({ selector: "app-upload", templateUrl: "./upload.component.html" })
export class UploadComponent {
validator = new FileValidator({
allowedTypes: [AllowedFileType.IMAGE, AllowedFileType.PDF],
maxSizeInMB: 10
});
async onFileChange(event: Event) {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
try { await this.validator.validate(file); }
catch (e: any) { alert(e.message); }
}
}React snippet
import React from "react";
import { FileValidator, AllowedFileType } from "universal-file-validator";
const validator = new FileValidator({
allowedTypes: [AllowedFileType.IMAGE, AllowedFileType.VIDEO],
maxSizeInMB: 15
});
export default function FileUpload() {
const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try { await validator.validate(file); alert("✅ Valid: " + file.name); }
catch (err: any) { alert("❌ " + err.message); }
};
return <input type="file" onChange={handleChange} />;
}⚙️ API
class FileValidator
constructor(options?: FileValidationOptions)
Creates a validator with your constraints.validate(file: File): Promise
Resolves when valid; rejects withErrorwhen invalid.
interface FileValidationOptions
export interface FileValidationOptions {
allowedTypes?: AllowedFileType[]; // Which types are allowed (optional)
maxSizeInMB?: number; // Max size in MB (optional, default 50)
minWidth?: number; // Min image width in px (optional, default 100)
minHeight?: number; // Min image height in px (optional, default 100)
}enum AllowedFileType
export enum AllowedFileType {
IMAGE = "image",
PDF = "pdf",
WORD = "word",
EXCEL = "excel",
ZIP = "zip",
VIDEO = "video",
POWERPOINT = "powerpoint",
TEXT = "text",
CSV = "csv",
AUDIO = "audio",
}✅ What’s validated under the hood
Images
- File header (magic numbers): PNG (
89504e47), JPEG (ffd8ffe0/1/2), GIF (47494638) - Minimum width/height via
Imageload
- Magic number
%PDF(25504446)
Word (DOCX)
- Opens ZIP and checks presence of
word/document.xml
Excel (XLSX)
- Opens ZIP and checks presence of
xl/workbook.xml
PowerPoint (PPTX)
- Opens ZIP and checks presence of
ppt/presentation.xml
ZIP
- Attempts to open with
JSZip.loadAsync(throws = invalid)
Video (basic)
- Reads first bytes and checks for common signatures:
- MP4/ISO BMFF (prefix with box size headers like
00000018,00000020) - Matroska/WebM (
1a45dfa3) - AVI/RIFF (
52494646)
- MP4/ISO BMFF (prefix with box size headers like
Audio (basic)
- Checks for:
- MP3 ID3 (
494433) or frame sync (fff3) - WAV/RIFF (
52494646) - OGG (
4f676753)
- MP3 ID3 (
Text
- Ensures file has non-empty text content
CSV
- Ensures file contains at least one comma (very simple sanity check)
These checks are intentionally lightweight. For stricter validation (e.g., CSV schema, media codec parsing), extend the validator to your needs.
🔧 Build & Test (for contributors)
npm install
npm run build
npm testIf you plan to publish:
npm publish --access public📁 Project setup (single-file package)
universal-file-validator/
├─ index.ts # your FileValidator source (exports class & enum)
├─ package.json
├─ tsconfig.json
└─ dist/ # generated by `npm run build`tsconfig.json (example):
{
"compilerOptions": {
"target": "ES2019",
"module": "CommonJS",
"declaration": true,
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["index.ts"]
}❓ FAQ
Are size and dimensions optional?
Yes. If you omit them, defaults are used:maxSizeInMB=50,minWidth=100,minHeight=100(dimensions only affect images).Why did my valid media file fail?
Magic-number checks are minimal. Some files may start differently. Extend thevalidateVideo/validateAudioarrays if needed.Does it work in Node.js?
It’s designed for the browser. To run in Node, you’ll need polyfills forFile,FileReader,Image, andURL.createObjectURL.
📜 License
MIT © Mohamed Saleh
