zinbar20
v1.0.0
Published
Data Validation Library: Develop a library for validating data inputs in JavaScript applications, supporting common validation rules such as required fields, data types, and custom validation functions.
Downloads
2
Readme
Data Validation Library
A lightweight JavaScript library for data validation, allowing you to define and apply validation rules to your data objects.
Installation
You can install the Data Validation Library via npm:
npm install data-validation-library
Usage
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);
}
API
Validator
Class
constructor()
Creates a new instance of the Validator class.
addRule(fieldName, type, options)
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.
validate(data)
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.
validators
Object
Contains built-in validators for common data types:
string(value, options)
number(value, options)
boolean(value, options)
License
This library is licensed under the MIT License.