node-easyvalid
Version:
A lightweight, powerful validation library for Node.js backend development. Simplify user input validation, error handling, and data integrity in Express APIs and JavaScript applications with ease.
76 lines (70 loc) • 2.31 kB
JavaScript
// src/index.js
// Single value validation
const isTrue = (value, message = "Validation Failed", statusCode = 400) => {
if (!value) {
const error = new Error(message);
error.statusCode = statusCode;
throw error;
}
return true;
};
// Array values validation
const isTrues = (array, message = "Validation Failed", statusCode = 400) => {
if (!Array.isArray(array)) {
const error = new Error("Input must be an array");
error.statusCode = statusCode;
throw error;
}
if (array.length === 0) {
const error = new Error("Array cannot be empty");
error.statusCode = statusCode;
throw error;
}
array.forEach((value, index) => {
if (!value) {
const error = new Error(`${message} at index ${index}`);
error.statusCode = statusCode;
throw error;
}
});
return true;
};
// Email validation
const isEmail = (email, message = "Invalid email format", statusCode = 400) => {
if (typeof email !== "string") {
const error = new Error("Email must be a string");
error.statusCode = statusCode;
throw error;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
const error = new Error(message);
error.statusCode = statusCode;
throw error;
}
return true;
};
// Minimum length validation
const minLength = (value, min, message = `Must be at least ${min} characters`, statusCode = 400) => {
if (typeof value !== "string") {
const error = new Error("Input must be a string");
error.statusCode = statusCode;
throw error;
}
if (value.length < min) {
const error = new Error(message);
error.statusCode = statusCode;
throw error;
}
return true;
};
// Number validation
const isNumber = (value, message = "Must be a number", statusCode = 400) => {
if (typeof value === "boolean" || isNaN(value) || value === null || value === "") {
const error = new Error(message);
error.statusCode = statusCode;
throw error;
}
return true;
};
module.exports = { isTrue, isTrues, isEmail, minLength, isNumber };