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

@unidev-hub/validator

v1.0.0

Published

Validation library for UniDev Hub applications

Readme

@unidev-hub/validator

A flexible and powerful validation library for TypeScript applications.

Features

  • 🔍 Type-safe validations with TypeScript
  • 🧩 Fluent API for creating complex validation rules
  • 🚦 Pre and post validation transforms
  • 📝 Detailed validation error messages
  • 🔄 Built on top of Joi for robustness
  • 🧰 Specialized validators for common types
  • 🌐 Integration with other UniDev Hub packages

Installation

npm install @unidev-hub/validator --save

Basic Usage

import { v } from '@unidev-hub/validator';

// Create a simple string validator
const nameValidator = v.string().required().min(2).max(50);

// Validate a value
const result = nameValidator.validate('John');
if (result.valid) {
  console.log('Valid name:', result.value);
} else {
  console.error('Invalid name:', result.error?.message);
}

// Validate or throw
try {
  const name = nameValidator.validateOrThrow('J');
} catch (error) {
  console.error('Validation failed:', error.message);
}

Object Validation

import { v } from '@unidev-hub/validator';

// Define a user schema
const userSchema = v.objectFrom({
  name: v.string().required().min(2).max(50),
  email: v.email().required(),
  age: v.number().integer().min(18).optional(),
  roles: v.array().items(v.string()).min(1),
  metadata: v.object().allowUnknown(true)
});

// Validate a user object
const user = {
  name: 'John Doe',
  email: '[email protected]',
  age: 25,
  roles: ['user'],
  metadata: {
    lastLogin: new Date(),
    preferences: { theme: 'dark' }
  }
};

const result = userSchema.validate(user);

Array Validation

import { v } from '@unidev-hub/validator';

// Array of strings
const tagsValidator = v.array()
  .items(v.string().min(2).max(20))
  .min(1)
  .max(10)
  .unique();

// Array of objects
const usersValidator = v.array()
  .items(
    v.objectFrom({
      id: v.string().required(),
      name: v.string().required()
    })
  )
  .min(1);

Custom Validations

import { v, CustomValidator } from '@unidev-hub/validator';

// Create a custom validator
const passwordValidator = v.string()
  .required()
  .min(8)
  .max(100)
  .custom((value) => {
    // At least one uppercase letter
    if (!/[A-Z]/.test(value)) {
      return 'Password must contain at least one uppercase letter';
    }
    
    // At least one lowercase letter
    if (!/[a-z]/.test(value)) {
      return 'Password must contain at least one lowercase letter';
    }
    
    // At least one number
    if (!/[0-9]/.test(value)) {
      return 'Password must contain at least one number';
    }
    
    // At least one special character
    if (!/[^A-Za-z0-9]/.test(value)) {
      return 'Password must contain at least one special character';
    }
    
    return true;
  });

Transforms

import { v } from '@unidev-hub/validator';

// Transform before validation
const trimmedEmailValidator = v.email()
  .withPreTransform(value => typeof value === 'string' ? value.trim() : value);

// Transform after validation
const userIdValidator = v.string().uuid()
  .withPostTransform(value => `user_${value}`);

Error Handling

import validator, { ValidationError } from '@unidev-hub/validator';

try {
  // Validate something
} catch (error) {
  if (error instanceof ValidationError) {
    // Format the error
    const message = validator.errors.formatValidationError(error);
    console.error(message);
    
    // Group errors by field
    const groupedErrors = validator.errors.groupValidationErrors(error);
    console.log(groupedErrors);
    
    // Check for specific field errors
    if (validator.errors.hasFieldError(error, 'email')) {
      const emailError = validator.errors.getFieldErrorMessage(error, 'email');
      console.error('Email error:', emailError);
    }
  }
}

Integration with Express

import express from 'express';
import { v } from '@unidev-hub/validator';
import { errors } from '@unidev-hub/validator';

const app = express();
app.use(express.json());

// Create a validator middleware
function validate(schema, location = 'body') {
  return (req, res, next) => {
    try {
      const result = schema.validate(req[location]);
      if (result.valid) {
        req[location] = result.value;
        next();
      } else {
        // Format for API response
        const formattedError = errors.validationErrorToResponse(result.error);
        res.status(400).json(formattedError);
      }
    } catch (error) {
      next(error);
    }
  };
}

// User creation schema
const createUserSchema = v.objectFrom({
  name: v.string().required().min(2),
  email: v.email().required(),
  password: v.string().required().min(8)
});

// Use in route
app.post('/users', validate(createUserSchema), (req, res) => {
  // req.body is now validated and sanitized
  res.status(201).json({ success: true, data: req.body });
});

Available Validators

  • v.string() - String validation
  • v.number() - Number validation
  • v.object() - Object validation
  • v.array() - Array validation
  • v.date() - Date validation
  • v.custom() - Custom validation
  • v.email() - Email validation
  • v.uuid() - UUID validation
  • v.url() - URL validation
  • v.integer() - Integer validation
  • v.positive() - Positive number validation
  • v.port() - Port number validation
  • v.boolean() - Boolean validation
  • v.futureDate() - Future date validation
  • v.pastDate() - Past date validation
  • v.isoDate() - ISO date validation
  • v.enum() - Enum validation

License

MIT