burhan-req-validator
Version:
A lightweight and customizable field validation library using Joi, inspired by Laravel's validation rules. Simplifies data validation with intuitive rule-based syntax.
79 lines (62 loc) • 2.47 kB
Markdown
# Custom Validator
A lightweight and customizable field validation library using Joi, inspired by Laravel's validation rules. Simplifies data validation with intuitive rule-based syntax.
## Installation
npm install burhan-req-validator
## Usage
const { validateFields } = require('burhan-req-validator');
const data = {
channel_id: "12345",
tags: ["sports", "music"],
isActive: true
};
const rules = {
channel_id: "required|string",
tags: "array|items:string",
isActive: "required|boolean"
};
const { error } = validateFields(data, rules);
if (error) {
console.log("Validation Error:", error.details.map(detail => detail.message));
} else {
console.log("Validation Passed!");
}
## Complex Validation
const { validateFields } = require('burhan-req-validator');
const data = {
username: "JohnDoe",
age: 25,
tags: ["sports", "music"],
profile: { bio: "Hello world!" },
birthDate: "1990-01-01",
isActive: true
};
const rules = {
username: "required|string|min:3|max:20",
age: "required|integer|min:18",
tags: "array|items:string",
profile: "object",
birthDate: "required|date",
isActive: "required|boolean"
};
const { error } = validateFields(data, rules);
if (error) {
console.log("Validation Error:", error.details.map(detail => detail.message));
} else {
console.log("Validation Passed!");
}
## Roles
Supported rules:
- **required**: Field is required.
- **string**: Validates that the field is a string.
- **email**: Validates that the field is a valid email address.
- **max:<value>**: Specifies the maximum length or value.
- **min:<value>**: Specifies the minimum length or value.
- **integer**: Validates that the field is an integer.
- **number**: Validates that the field is a number.
- **boolean**: Validates that the field is a boolean (`true` or `false`).
- **date**: Validates that the field is a valid date.
- **object**: Validates that the field is an object.
- **array**: Validates that the field is an array.
- **items:<type>**: Specifies the type of elements within the array (e.g., `items:string`, `items:number`).
- **nullable**: Allows the field to be `null`.
- **regex:<pattern>**: Validates the field against a custom regular expression.