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

data-validation-proximity

v1.3.8

Published

A library of Joi-based validation middlewares for Express.js

Readme

Data Validation Proximity

A comprehensive library of Joi-based validation middlewares for Express.js applications, specifically designed for e-commerce platforms with complex data structures.

Installation

npm install data-validation-proximity

Dependencies

This package requires Joi for validation:

npm install joi@^17.x

Usage

Basic Setup

const express = require('express');
const { 
  validateUser, 
  validateProduct, 
  validateStore 
} = require('data-validation-proximity');

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

// Apply validation middleware to routes
app.post('/api/users', validateUser, (req, res) => {
  // req.body is validated
  res.json({ message: 'User created' });
});

app.post('/api/products', validateProduct, (req, res) => {
  // req.body is validated and preprocessed
  res.json({ message: 'Product created' });
});

app.post('/api/stores', validateStore, (req, res) => {
  // req.body is validated
  res.json({ message: 'Store created' });
});

Available Validation Middlewares

User & Authentication

  • validateUser - Validates user registration/creation
  • validateUserUpdate - Validates user profile updates
  • validateLogin - Validates login credentials
  • validateResetPassword - Validates password reset requests

Store Management

  • validateStore - Validates store creation with full details
  • validateStoreUpdate - Validates store information updates
  • validateStoreCategory - Validates store category data
  • validateStoreRate - Validates store rating submissions

Product Management

  • validateProduct - Validates product creation with images and variants
  • validateProductUpdate - Validates product updates
  • validateCategory - Validates product category data

Orders & Transactions

  • validateOrder - Validates order placement
  • validateCart - Validates shopping cart data
  • validateBill - Validates billing information
  • validatePayment - Validates payment transactions
  • validatePaymentType - Validates payment method types

Promotions & Offers

  • validateOffer - Validates special offers/promotions
  • validateFlashDeal - Validates flash sale deals
  • validateReductionOffer - Validates discount offers

Subscriptions

  • validatePlan - Validates subscription plans
  • validateSubscription - Validates subscription data
  • validateSubscriptionOffer - Validates subscription offer details

Other

  • validateNotification - Validates notification data
  • validateSale - Validates sales records
  • validateView - Validates view tracking data
  • validateUserAction - Validates user activity tracking

Features

Automatic Data Preprocessing

The library includes intelligent preprocessing for complex data:

JSON Field Parsing

Automatically parses stringified JSON fields:

// Before validation, string fields are parsed to objects
app.post('/api/products', validateProduct, (req, res) => {
  // req.body.variants: "[{...}]" → [{...}]
  // req.body.policy: "{...}" → {...}
});

File Array Normalization

Normalizes file uploads for consistent handling:

// Single file uploads are converted to arrays
app.post('/api/products', validateProduct, (req, res) => {
  // req.files.images: single file → [file]
  // req.files.varientsImages: single file → [file]
});

Complex Schema Support

Address Schema

{
  latitude: Number,
  longitude: Number,
  countryCode: String (min 2 chars),
  country: String (min 3 chars),
  city: String (min 3 chars),
  streetName: String (min 3 chars),
  postalCode: String (min 3 chars),
  fullAdress: String,
  region: String,
  apartmentNumber: String
}

Working Time Schema

{
  option: String (required),
  fixedHours: [{
    openTime: String,
    closeTime: String
  }],
  customizedHours: {
    [dayName]: [{
      openTime: String,
      closeTime: String
    }]
  }
}

Policy Schema

Comprehensive policy validation for:

  • Working hours
  • Pickup policies
  • Delivery options
  • Reservation rules (duration, payment, cancellation)
  • Return policies (duration, conditions, refunds)
  • Order management (validation, notifications)

Role Validation

Built-in support for role-based validation:

// Valid roles: 'user', 'admin', 'seller', 'paymentManager', 'manager', 'SuperManager'

Examples

User Registration

const { validateUser } = require('data-validation-proximity');

app.post('/api/register', validateUser, async (req, res) => {
  // req.body contains validated data:
  // - username, email, password, phone
  // - optional: address, profileImage, etc.
  const user = await User.create(req.body);
  res.status(201).json(user);
});

Product Creation

const { validateProduct } = require('data-validation-proximity');

app.post('/api/products', validateProduct, async (req, res) => {
  // Automatically preprocessed:
  // - JSON strings parsed to objects
  // - File arrays normalized
  // - Validated: name, price, category, variants, policy
  const product = await Product.create(req.body);
  res.status(201).json(product);
});

Store Setup

const { validateStore } = require('data-validation-proximity');

app.post('/api/stores', validateStore, async (req, res) => {
  // Validated data includes:
  // - store details (name, description, category)
  // - address with coordinates
  // - working hours
  // - policies
  // - payment methods
  const store = await Store.create(req.body);
  res.status(201).json(store);
});

Order Placement

const { validateOrder } = require('data-validation-proximity');

app.post('/api/orders', validateOrder, async (req, res) => {
  // Validated: products, amounts, addresses, payment info
  const order = await Order.create(req.body);
  res.status(201).json(order);
});

Error Handling

Validation errors return a 400 status with detailed error messages:

// Invalid request
{
  "error": "\"email\" must be a valid email"
}

// Multiple validation errors
{
  "error": "\"price\" must be a positive number"
}

Integration with Custom Error Library

Works seamlessly with custom-error-library:

const { errorMiddleware } = require('custom-error-library');
const { validateProduct } = require('data-validation-proximity');

app.post('/api/products', validateProduct, createProduct);

// Error middleware handles validation errors
app.use(errorMiddleware);

Advanced Usage

Custom Validation Middleware

You can create custom validation middlewares using the exported helper:

const { createValidationMiddleware } = require('data-validation-proximity');
const Joi = require('joi');

const customSchema = Joi.object({
  customField: Joi.string().required()
});

const validateCustom = createValidationMiddleware(customSchema);

app.post('/api/custom', validateCustom, handler);

Preprocessing Hooks

For complex data transformations, validation middlewares include preprocessing:

// Example: Product validation with preprocessing
// 1. Parses JSON strings (variants, policy, etc.)
// 2. Normalizes file arrays
// 3. Validates against schema
// 4. Passes to route handler

Best Practices

  1. Apply validation early - Use validation middleware before business logic
  2. Combine with error handling - Use with custom-error-library for consistent errors
  3. Use appropriate validators - Choose specific validators (validateUser vs validateUserUpdate)
  4. Handle file uploads - Validation automatically normalizes file arrays
  5. Trust preprocessed data - Data is cleaned and parsed before validation

Schema Reference

Common Field Types

| Field Type | Validation Rules | Example | |------------|-----------------|---------| | Email | Valid email format | [email protected] | | Phone | String, min 8 chars | +1234567890 | | Password | String, min 6 chars | securePass123 | | Price | Positive number | 29.99 | | Coordinates | Number (lat/lng) | 34.0522, -118.2437 | | URL | Valid URL format | https://example.com | | Role | Enum of valid roles | seller, admin |

License

MIT