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 🙏

© 2026 – Pkg Stats / Ryan Hefner

universal-file-validator

v1.0.1

Published

File validation library for images, documents, videos, audio, and archives

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, and Image. 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 with Error when 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 Image load

PDF

  • 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)

Audio (basic)

  • Checks for:
    • MP3 ID3 (494433) or frame sync (fff3)
    • WAV/RIFF (52494646)
    • OGG (4f676753)

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 test

If 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 the validateVideo/validateAudio arrays if needed.

  • Does it work in Node.js?
    It’s designed for the browser. To run in Node, you’ll need polyfills for File, FileReader, Image, and URL.createObjectURL.


📜 License

MIT © Mohamed Saleh