UNPKG

validation-box

Version:

The only validation library - with flexible regex - you need.

110 lines (108 loc) 2.95 kB
import { validateAge, validateEmail, validatePassword, validateUser, validateUsername } from "./chunk-TAG6UVFN.mjs"; // src/schemas/index.ts var vboxSchema = class _vboxSchema { rules; validateAll; showErrors; constructor(rules, options) { this.rules = rules; this.validateAll = options?.validateAll ?? false; this.showErrors = options?.showErrors ?? true; } transformValue(value, transforms) { if (!transforms) return value; return transforms.reduce((acc, transform) => transform(acc), value); } validate(data) { const validatedData = {}; const errors = {}; let isValid = true; for (const field in this.rules) { const rule = this.rules[field]; const value = data[field]; const options = rule.options || {}; if (options.required && (value === void 0 || value === null || value === "")) { isValid = false; const message = options.messages?.required || `${field} is required`; errors[field] = [message]; if (!this.validateAll) break; continue; } if (!options.required && (value === void 0 || value === null || value === "")) { continue; } const transformedValue = this.transformValue(value, rule.transform); const validation = rule.fn(transformedValue, options); if (validation.valid) { validatedData[field] = transformedValue; } else { isValid = false; const errorMessages = validation.errors || []; errors[field] = errorMessages; if (!this.validateAll) break; } } return { success: isValid, data: isValid ? validatedData : void 0, errors: !isValid && this.showErrors ? errors : void 0 }; } // Method to add custom validation rule addRule(field, rule) { this.rules[field] = rule; return this; } // Method to extend schema with another schema extend(schema) { return new _vboxSchema({ ...this.rules, ...schema["rules"] }); } // Method to resolve validation for form data resolve(data, returnAllErrors = false) { const result = this.validate(data); return { values: result.success ? data : {}, errors: result.errors ? Object.keys(result.errors).reduce((acc, key) => { const errorMessages = result.errors?.[key] || []; acc[key] = { type: "manual", messages: returnAllErrors ? errorMessages : [errorMessages[0]] }; return acc; }, {}) : {} }; } }; var validator = { username: (options) => ({ fn: validateUsername, options }), user: (options) => ({ fn: validateUser, options }), email: (options) => ({ fn: validateEmail, options }), password: (options) => ({ fn: validatePassword, options }), age: (options) => ({ fn: validateAge, options }) }; export { vboxSchema, validator }; //# sourceMappingURL=chunk-UNIGDQBQ.mjs.map