Validate.js: Declarative JavaScript Validations

0.13.1 · maintenance · verified Sun Apr 19

validate.js provides a declarative, schema-based approach for validating JavaScript objects, suitable for both client-side and server-side applications. The current stable version is 0.13.1. While the release cadence appears to be moderate, the library has a long-standing history and focuses on stability and a comprehensive set of built-in validators, including new additions like a type validator. Its key differentiator lies in its concise, constraint-based syntax, allowing developers to define complex validation rules with minimal boilerplate. It is often chosen for projects requiring robust data integrity checks without external framework dependencies, and it ships with TypeScript types for improved developer experience and static analysis.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define validation constraints for a user object and use the default `validate` function to check the data integrity, handling both success and failure cases.

import validate from 'validate.js';

interface UserData {
  email?: string;
  password?: string;
  passwordConfirmation?: string;
  age?: number;
}

const user: UserData = {
  email: 'test@example.com',
  password: 'Password123!',
  passwordConfirmation: 'Password123!',
  age: 25
};

const constraints = {
  email: {
    presence: true,
    email: true
  },
  password: {
    presence: true,
    length: { minimum: 8, message: 'must be at least 8 characters' },
    format: {
      pattern: '[a-zA-Z0-9!@#$%^&*()_+]{8,}',
      message: 'can only contain letters, numbers, and common symbols'
    }
  },
  passwordConfirmation: {
    equality: 'password'
  },
  age: {
    numericality: { 
      onlyInteger: true, 
      greaterThanOrEqualTo: 18, 
      message: 'must be an integer 18 or older'
    },
    type: 'integer' // New type validator from 0.13.1
  }
};

const errors = validate(user, constraints);

if (errors) {
  console.error('Validation failed:\n', JSON.stringify(errors, null, 2));
} else {
  console.log('Validation successful!');
}

// Example of invalid data
const invalidUser: UserData = {
  email: 'invalid-email',
  password: 'short',
  passwordConfirmation: 'mismatch',
  age: 17.5
};

const invalidErrors = validate(invalidUser, constraints);
if (invalidErrors) {
  console.error('\nInvalid user validation failed as expected:\n', JSON.stringify(invalidErrors, null, 2));
}

view raw JSON →