UNPKG

legendaryjs

Version:

LegendaryJS – The ultimate backend framework for speed, power, and simplicity.

36 lines (27 loc) 994 B
function validate(data = {}, schema = {}) { const errors = []; for (const key in schema) { const rules = schema[key]; const value = data[key]; if (rules.required && (value === undefined || value === null || value === '')) { errors.push(`${key} is required`); } if (rules.type && typeof value !== rules.type.toLowerCase()) { errors.push(`${key} must be of type ${rules.type}`); } if (rules.min && typeof value === 'string' && value.length < rules.min) { errors.push(`${key} must be at least ${rules.min} characters`); } if (rules.max && typeof value === 'string' && value.length > rules.max) { errors.push(`${key} must be at most ${rules.max} characters`); } if (rules.enum && !rules.enum.includes(value)) { errors.push(`${key} must be one of: ${rules.enum.join(', ')}`); } } return { valid: errors.length === 0, errors }; } module.exports = { validate };