dx-json-schema-validator
v1.0.1
Published
Dynamic schema validation library
Readme
Dynamic JSON Schema Validator 🚀
A zero-dependency (conceptually, powered by Zod) dynamic form validation engine. Convert static JSON configurations into robust, recursive Zod schemas on the fly.
Perfect for SaaS applications, dynamic form builders, and multi-tenant architectures where validation rules come from a database or API.
✨ Features
- JSON to Zod: Define your validation rules in pure JSON.
- Recursive Sub-forms: Easily handle infinitely nested object structures.
- Conditional Logic: Show, hide, or ignore fields based on other field values (
if/then/else). - Standardized Error Codes: Outputs clean, predictable error keys powered by Zod issues.
- Framework Agnostic: Works perfectly with React, Vue, Node.js, or Vanilla JS.
📦 Installation
Install the package using your favorite package manager:
npm install dx-json-schema-validator
# or
pnpm add dx-json-schema-validator
# or
yarn add dx-json-schema-validator💻 Basic Usage
Define your schema in JSON and pass it to the validateForm engine along with your data.
import { validateForm, type FormField } from 'dx-json-schema-validator';
// 1. Define your dynamic schema (usually fetched from an API)
const schema: FormField[] = [
{
component: 'text-field',
key: 'username',
label: 'User Name',
validation: {
required: true,
minLength: 3,
errorMessages: { required: 'Username is mandatory' }
}
}
];
// 2. Validate your data
const formData = { username: 'Fa' };
const result = validateForm(formData, schema);
if (!result.success) {
console.log(result.errors);
/* Output:
[
{
path: 'username',
message: 'Must be at least 3 characters long',
key: 'too_small'
}
]
*/
}🔀 Advanced: Conditional Logic
You can conditionally validate fields based on the state of other fields in the form data.
import { type FormField } from 'dx-json-schema-validator';
const schema: FormField[] = [
{
component: 'select',
key: 'role',
label: 'User Role'
},
{
component: 'text-field',
key: 'adminCode',
conditional: {
if: { field: 'role', operator: 'equals', value: 'admin' },
then: ['show'],
else: ['hide']
},
validation: { required: true }
}
];
// If role is 'guest', 'adminCode' validation is completely skipped!