@softwareproduction/dryvjs
v1.0.1
Published
<p align="center"> <img src="public/logo.svg" title="Dryv" width="300"><br> <span style="font-size: 24px; font-weight: bold;">DRY Validation for Distributed Apps</span> </p>
Readme
DryvJS is the core, framework-agnostic validation library that powers the Dryv ecosystem. It provides a complete validation engine that builds a tree of validators mirroring your data model. It supports nested objects, arrays, async rules, server-side validation, and dirty tracking.
DryvJS can be used standalone using rule sets defined directly in TypeScript. It is also designed as the client-side runtime for validation rules generated by Dryv (.NET).
Note: For Vue 3 integration, see Dryvue.
Table of Contents
- Installation
- Why DryvJS?
- Core Concepts
- Usage Guide
- Validator Hierarchy
- API Reference
- Using with Dryv (C#/.NET)
- License
Installation
npm install @softwareproduction/dryvjsWhy DryvJS?
- Decoupled Business Logic: Validation rules are defined against your data models, independent of your UI components.
- Recursive Validation Trees: Seamlessly validates complex, deeply nested objects and arrays using dot-notation.
- Deep Reactivity: Advanced dirty tracking with
commit()andrevert()semantics integrated directly into the validation state. - Full-Stack Synergy: Effortlessly executes C# validation rules translated to JavaScript when using Dryv for .NET.
Core Concepts
Validation Rule Sets
A DryvValidationRuleSet maps validation rules to fields on your model. You can use dot-notation to define rules for nested properties.
import type { DryvValidationRuleSet } from 'dryvjs'
interface SignupForm {
username: string
age: number
}
const ruleSet: DryvValidationRuleSet<SignupForm> = {
name: 'SignupForm',
validators: {
username: [
{
annotations: { required: true },
validate: ($m) => !$m.username ? 'Username is required' : null
}
],
age: [
{
validate: ($m) => $m.age < 18
? { type: 'error', text: 'Must be at least 18 years old' }
: null
}
]
}
}Validation Result Types
Rules can return null (for success), a string (shorthand for an error), or a DryvFieldValidationResult object to categorize the result:
interface DryvFieldValidationResult {
path?: string
type?: 'error' | 'warning' | 'success'
text?: string | null
group?: string | null
}Usage Guide
Setting Up a Validation Session
To validate an object, you instantiate a DryvValidationSession and a DryvObjectValidator:
import {
DryvValidationSession,
DryvObjectValidator,
defaultDryvOptions
} from 'dryvjs'
const model = { username: '', age: 0 }
const options = { ...defaultDryvOptions }
const session = new DryvValidationSession(options, ruleSet)
const validator = new DryvObjectValidator(model, session, undefined, options)
// Validate the entire model
const result = await validator.validate()
console.log(result.success) // false
console.log(result.hasErrors) // trueNested Object & Array Validation
Target deeply nested fields naturally by leveraging dot-notation. The validator handles array indexing automatically.
const ruleSet: DryvValidationRuleSet<Course> = {
name: 'Course',
validators: {
'address.city': [
{ validate: ($m) => !$m.city ? 'City required' : null }
],
// Array target: applies to every attendee in the array
'people.attendees.name': [
{ validate: ($m: Attendee) => !$m.name ? 'Attendee name required' : null }
]
}
}Async & Server-Side Validation
Mark rules as async: true and delegate complex logic to the server. DryvJS handles asynchronous resolutions automatically.
email: [
{
async: true,
validate: ($m, session) => {
return session.dryv
.callServer('/api/validate-email', 'POST', { email: $m.email })
.then(($r) => session.dryv.handleResult(session, $m, 'email', null, $r))
}
}
](Note: The default callServer utilizes fetch. You can override this in options).
Related Fields & Grouped Messages
When changing one field should re-validate another, use related. You can also assign messages to a group to display them collectively.
email: [
{
related: ['phone'],
validate: ($m) => !$m.phone && !$m.email
? { type: 'error', text: 'Provide email or phone', group: 'contact' }
: null
}
]Disablers & Parameters
Conditionally disable rules, and inject dynamic parameters into your validation logic:
const ruleSet: DryvValidationRuleSet<MyForm, MyParameters> = {
name: 'MyForm',
validators: { /* ... */ },
disablers: {
// Skip title validation if the user is a guest
title: [{ validate: ($m) => $m.role === 'guest' }]
},
parameters: {
maxBirthDate: '2005-11-28'
}
}Warnings vs. Errors
Rules can yield warnings. Warnings do not cause validation to fail but provide user feedback.
{
validate: ($m) => !$m.middleName
? { type: 'warning', text: 'Middle name is recommended' }
: null
}Dirty Tracking
The validator monitors all changes from the initial object state:
validator.isDirty // false
model.username = 'new name'
validator.isDirty // true
// Baseline management:
validator.commit() // Establish current state as the new pristine state
validator.revert() // Discard changes, reverting back to the last committed stateValidation Triggers
Choose when validation executes by setting validationTrigger in the options:
'immediate': Validate immediately, including before the user has made any changes.'auto': Validate automatically on field changes, but not during initialization.'manual': Only validate whenvalidate()is explicitly called.'autoAfterManual': The default. Only validates during explicitvalidate()calls initially; after the firstvalidate()call, also validates automatically on field changes.
Customizing Options
Provide an options object to customize core behaviors like network requests or date parsing:
const options: DryvOptions = {
...defaultDryvOptions,
baseUrl: 'https://api.example.com',
exceptionHandling: 'failValidation',
callServer: async (url, method, data) => {
// Implement custom Axios logic or add Auth headers here
}
}Validator Hierarchy
DryvValidator (abstract base)
├── DryvFieldValidator — Leaf validator for scalar fields
└── DryvCompositeValidator — Base for composite validators
├── DryvObjectValidator — Validates objects with named fields
└── DryvArrayValidator — Validates arrays of itemsDryvFieldValidator: Wraps a single scalar value.DryvObjectValidator: Wraps an object. Implements aProxyto intercept mutations and trigger reactivity.DryvArrayValidator: Wraps an array. Intercepts array mutations (push,splice, etc.) to organically keep the validation tree in sync.
API Reference
DryvValidationSession
validateObject(validator): Validates the full object tree.validateField(field, model?): Validates a specific field.parameter(key): Retrieve an injected parameter.reset(): Clears validation triggered states.results.fields&results.groups: Dictionaries holding validation results.
DryvValidator
- Properties:
value,path,text,type,group,required,hasErrors,isSuccess,isDirty. - Methods:
validate(),clear(),commit(),revert(),setValidationResult(response).
Using with Dryv (C#/.NET)
DryvJS is the intended client-side runtime for Dryv. Dryv directly outputs rule configurations that perfectly match DryvValidationRuleSet.
If you are using Dryv on the backend, you do not need to manually write rules in JavaScript. DryvJS consumes the auto-generated JavaScript object transparently, matching C# annotations and executing dynamic server routines cleanly.
For a full guide on setting up the C# translation and consuming it via Code Generation, Server-Rendered tag helpers, or API loading, see the Root README.
License
MIT
