Validate.js: Declarative JavaScript Validations
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
-
TypeError: validate is not a function
cause Attempting to destructure the default export using named import syntax (e.g., `import { validate } from 'validate.js';`) instead of a default import.fixUse a default import: `import validate from 'validate.js';` -
ReferenceError: validate is not defined
cause This error often occurs in a browser environment when `validate.js` is included via a script tag, but the global `validate` object is not accessible, or in Node.js when the module is not correctly imported.fixEnsure the script tag is loaded before your code, or if using CommonJS/ESM, verify the `require` or `import` statement is at the top of your file: `const validate = require('validate.js');` or `import validate from 'validate.js';`. -
TypeError: Cannot read properties of undefined (reading 'validators')
cause This typically happens when trying to access or extend `validate.validators` or other properties before the main `validate` object has been properly imported or initialized.fixConfirm that `validate` is correctly imported as a default export before attempting to access its properties or methods, e.g., `import validate from 'validate.js'; validate.extend(...);`
Warnings
- gotcha Versions prior to 0.13.1 might inadvertently leak variables to the global namespace when used in certain environments due to a missing 'var' keyword. It's recommended to upgrade to 0.13.1 or later to avoid potential global scope pollution.
- gotcha Earlier versions contained issues with the email validation logic that could lead to incorrect validation results (e.g., falsely validating invalid emails or rejecting valid ones). These issues were addressed in version 0.13.1.
Install
-
npm install validate.js -
yarn add validate.js -
pnpm add validate.js
Imports
- validate
import { validate } from 'validate.js';import validate from 'validate.js';
- validate.extend
import validate from 'validate.js'; validate.extend(validate.validators, { // custom validator }); - Constraints
import type { Constraints, Attributes, Errors } from 'validate.js';
Quickstart
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));
}