A lightweight JavaScript library for data validation, allowing you to define and apply validation rules to your data objects.
You can install the Data Validation Library via npm:
npm install data-validation-library
const { Validator, validators } = require('data-validation-library');
// Create a new instance of the Validator class
const validator = new Validator();
// Add validation rules for your fields
validator.addRule('username', 'string', { minLength: 3, maxLength: 20, message: 'Invalid username' });
validator.addRule('age', 'number', { min: 18, max: 100, message: 'Age must be between 18 and 100' });
// Define your data object
const data = {
username: 'john_doe',
age: 25
};
// Validate the data
const errors = validator.validate(data);
if (Object.keys(errors).length === 0) {
console.log('Data is valid!');
} else {
console.error('Validation errors:', errors);
}
Creates a new instance of the Validator class.
Adds a validation rule for a field.
-
fieldName
(string): The name of the field to validate. -
type
(string): The data type to validate (e.g., 'string', 'number', 'boolean'). -
options
(object, optional): Additional options for the validation rule, such as minimum length, maximum length, etc.
Validates a data object against the defined validation rules.
-
data
(object): The data object to validate.
Returns an object containing validation errors, where the keys are the field names and the values are the error messages.
Contains built-in validators for common data types:
string(value, options)
number(value, options)
boolean(value, options)
This library is licensed under the MIT License.