tiny-validate
v1.0.1
Published
A Super Lightweight, Chainable Data Validation Module
Maintainers
Readme
tiny-validate - Simple JavaScript Validator
A lightweight, chainable, and comprehensive data validation library for JavaScript.
Features
- Chainable API: Easily apply multiple validation rules in a single, readable line of code.
- Rich Rule Set: Includes a wide range of validation rules for strings, numbers, arrays, dates, and more.
- Clear Error Handling: Returns a detailed object with all validation errors, including the rule that failed and a descriptive message.
- Customizable: Override default error messages with your own for tailored feedback.
Installation
npm install tiny-validateUsage
- Import the Module First, import the createValidator factory function.
const { createValidator } = require('./index.js');- Basic Validation Use createValidator to start a validation chain for a specific value and field name.
const user = {
name: 'John',
email: '[email protected]',
age: 30
};
// Validate the 'name' field
const nameResult = createValidator('name', user.name)
.isNotEmpty('Name cannot be empty.')
.isString('Name must be a string.')
.minLength(2, 'Name must be at least 2 characters long.')
.validate();
console.log(nameResult);
/*
Output:
{
isValid: true,
errors: [],
value: 'John'
}
*/- Handling Validation Failures The validate() method returns an object with an isValid boolean and an errors array.
const user = {
name: 'A',
email: 'invalid-email',
age: 17
};
const validationResult = createValidator('user data', user)
.hasKey('name', 'User object must have a name.')
.hasKey('email')
.hasKey('age')
.validate();
const emailResult = createValidator('email', user.email)
.isEmail('Please enter a valid email address.')
.validate();
const ageResult = createValidator('age', user.age)
.isNumber('Age must be a number.')
.min(18, 'You must be at least 18 years old.')
.validate();
console.log('User Validation:', validationResult);
console.log('Email Validation:', emailResult);
console.log('Age Validation:', ageResult);
/*
Example Output:
User Validation: {
isValid: true,
errors: [],
value: { name: 'A', email: 'invalid-email', age: 17 }
}
Email Validation: {
isValid: false,
errors: [
{ rule: 'matches', message: 'Please enter a valid email address.' }
],
value: 'invalid-email'
}
Age Validation: {
isValid: false,
errors: [
{ rule: 'min(18)', message: 'You must be at least 18 years old.' }
],
value: 17
}
*/- Array Validation with .each() The .each() method is powerful for validating every item in an array.
const numbers = [1, 2, 'three', 4, 5];
const arrayResult = createValidator('numbers', numbers)
.isArray('Value must be an array.')
.each(item => createValidator('item', item).isInteger('All items must be integers.'))
.validate();
console.log(arrayResult);
/*
Output:
{
isValid: false,
errors: [
{
rule: 'each',
message: 'An item in the array failed validation: [{"rule":"isInteger","message":"All items must be integers."}]'
}
],
value: [1, 2, 'three', 4, 5]
}
*/JavaScript Best Practices This module is written to adhere to several key JavaScript best practices.
Immutability The validator object is designed to be immutable. Each method call returns a new instance of the validator with the updated state, ensuring that the original object remains unchanged.
Functional Programming The .each() method is a great example of functional programming principles. It accepts a function as an argument, allowing you to apply any validation logic to each element of an array, promoting reusable and modular code.
Clear Naming Conventions All methods and variables use clear, descriptive names (e.g., isNotEmpty, minLength, fieldName). This makes the code self-documenting and easy to understand at a glance.
Modularity (ES Modules) The module.exports = { createValidator } syntax follows the Node.js standard for exporting modules. This makes the code reusable and easy to integrate into larger projects.
Defensive Programming The check() method is a core example of defensive programming. It encapsulates the core logic of a validation rule, ensuring that a consistent error is added to the errors array if a condition is not met.
Code Style and Readability The code is well-formatted with consistent indentation and uses modern syntax (e.g., const and let), making it clean and readable.
| Option | Default | Description |
| :--- | :--- | :--- |
| isNotEmpty() | - | Validates that the value is not null, undefined, or an empty string. |
| isType(type) | - | Validates that the value is of the specified type ('string', 'number', 'boolean', etc.). |
| equals(value) | - | Validates that the value is strictly equal to the specified value. |
| notEquals(value) | - | Validates that the value is not strictly equal to the specified value. |
| oneOf(list) | - | Validates that the value is one of the elements in the specified array. |
| notOneOf(list) | - | Validates that the value is not one of the elements in the specified array. |
| isString() | - | Validates that the value is a string. |
| minLength(min) | - | Validates that the string has a minimum length. |
| maxLength(max) | - | Validates that the string has a maximum length. |
| matches(regex) | - | Validates that the string matches a specified regex pattern. |
| isEmail() | - | Validates that the value is a valid email address. |
| isURL() | - | Validates that the value is a valid URL. |
| isUUID() | - | Validates that the value is in a valid UUID format. |
| isIP() | - | Validates that the value is a valid IP address. |
| isCreditCard() | - | Validates that the value is a valid credit card number (using the Luhn algorithm). |
| isLowercase() | - | Validates that the entire value is in lowercase. |
| isUppercase() | - | Validates that the entire value is in uppercase. |
| isSlug() | - | Validates that the value is a valid slug (URL-friendly text). |
| isHexColor() | - | Validates that the value is a valid hex color code. |
| isIBAN() | - | Validates that the value is a valid IBAN. |
| isAlpha() | - | Validates that the value contains only letters. |
| isAlphaNumeric() | - | Validates that the value contains only letters and numbers. |
| notContainsAny(chars) | - | Validates that the value does not contain any of the specified characters. |
| isJSON() | - | Validates that the value is a valid JSON string. |
| startsWith(prefix) | - | Validates that the string starts with the specified prefix. |
| endsWith(suffix) | - | Validates that the string ends with the specified suffix. |
| isNumber() | - | Validates that the value is a number. |
| isInteger() | - | Validates that the value is an integer. |
| min(min) | - | Validates that the number is greater than or equal to the minimum value. |
| max(max) | - | Validates that the number is less than or equal to the maximum value. |
| isPositive() | - | Validates that the number is positive. |
| isNegative() | - | Validates that the number is negative. |
| isBetween(min, max) | - | Validates that the number is within the specified range. |
| isArray() | - | Validates that the value is an array. |
| isUnique() | - | Validates that all elements in the array are unique. |
| arrayLength(length) | - | Validates that the array has the specified length. |
| arrayMinLength(length) | - | Validates that the array has a minimum length. |
| arrayMaxLength(length) | - | Validates that the array has a maximum length. |
| each(validatorFn) | - | Validates each element in the array using a specified validation function. |
| isDate() | - | Validates that the value is a valid Date object. |
| isAfter(date) | - | Validates that the date is after the specified date. |
| isBefore(date) | - | Validates that the date is before the specified date. |
| isFuture() | - | Validates that the date is in the future. |
| isPast() | - | Validates that the date is in the past. |
| isTruthy() | - | Validates that the value is "truthy" in JavaScript. |
| isFalsy() | - | Validates that the value is "falsy" in JavaScript. |
| contains(substring) | - | Validates that the string contains a specified substring. |
| notContains(substring) | - | Validates that the string does not contain a specified substring. |
| isEqualCaseInsensitive(value) | - | Validates that the string is equal to the specified value, ignoring case. |
| isPostalCode() | - | Validates that the value is a 5-digit postal code. |
| isPhoneNumber() | - | Validates that the value matches a general phone number format. |
| hasKey(key) | - | Validates that the object has the specified key. |
