
Why validation gets written twice
Almost every web application validates the same data twice. The browser checks that an email address looks like an email address, so the person filling in the form finds out before they press submit. The server checks it again, because anything arriving over HTTP is a claim rather than a fact. Both checks are necessary, and neither can be removed.
The trouble is that they are usually two separate pieces of code, written in two places, at two different times. They drift. A minimum password length moves from eight characters to ten on the server, nobody updates the form, and users are rejected after submitting with no explanation of what went wrong. A field becomes optional in the API while the client still insists on it. A category list grows by one entry in the backend and the dropdown never hears about it.
None of these are dramatic bugs. They are small, and they are expensive, because they only surface at the boundary between two systems that each look perfectly correct when read on their own. Teams end up writing separate validation logic for frontend and backend, managing more than one validation library across environments, and keeping the two consistent by hand.
IsoValid is a lightweight, isomorphic validation library that lets you define a rule once and run the identical code in both browser and Node.js environments.
What IsoValid is
IsoValid is a TypeScript-first validation library designed to unify validation across the whole application stack. Whether you are validating user input in a React form or checking the body of a request in an Express route, the schema is the same object, imported from the same package, behaving the same way.
It is deliberately small. Version 1.0.4 ships thirteen files and unpacks to roughly 19 KB, has no runtime dependencies at all, and brings its own type definitions rather than relying on a separate @types package. It is MIT licensed, and the test suite covers more than 88% of the code.
Key features
- True isomorphic support. The same validation code runs in both frontend and backend.
- TypeScript-first. A fully typed API, built for strong type inference.
- Minimal bundle size. No unnecessary dependencies or bloat.
- Intuitive API. A developer-friendly, chainable syntax.
- High performance. Optimized validation with minimal overhead.
- Extensible. Custom validators and error messages are easy to add.
Installation
bash npm install isovalid
Core architecture
IsoValid is built on a flexible, extensible architecture that includes:
Base schema class
- Foundation for all validation schemas
- Handles optional and nullable states
- Common validation logic across types
Type-specific schemas
- StringSchema, for length, regex, email and trimming
- NumberSchema, for min and max, integers, and positive or negative checks
- More types to come, including boolean, array and object
Validation pipeline
- A multi-stage validation process
- Support for custom validation functions
- Detailed error reporting
Usage
String validation
```ts import { v } from 'isovalid';
const stringSchema = v.string() .min(2) // Minimum length .max(50) // Maximum length .email() // Must be a valid email .matches(/regex/) // Custom pattern .trimmed() // Remove extra whitespace .setOptional() // Allow undefined .setNullable(); // Allow null ```
Every method returns the schema, so rules read in the order you would say them out loud, and a schema is just a value. You can build one in a shared module, export it, and import it from anywhere.
Number validation
ts const numberSchema = v.number() .min(0) // Minimum value .max(100) // Maximum value .integer() // Must be an integer .positive(); // Must be > 0
Validation results
ts interface ValidationResult { valid: boolean; errors: Array<{ path: string[]; message: string; }>; }
This shape matters more than it looks. Validation never throws, so there is no try/catch wrapped around ordinary user mistakes, and a failed check is a value you can inspect rather than control flow you have to catch. Because every error carries a path as well as a message, you can map errors straight onto form fields instead of showing one generic banner, and the same array can be serialised into a JSON error response without reshaping it.
Real-world examples
React form validation
```tsx import { v } from 'isovalid'; import { useState, FormEvent } from 'react';
const userSchema = { username: v.string().min(3).max(20), email: v.string().email(), age: v.number().integer().min(18) };
function RegistrationForm() { const [formData, setFormData] = useState({ username: '', email: '', age: '' }); const [errors, setErrors] = useState<Record<string, string>>({});
const validateField = (field: keyof typeof userSchema, value: any) => { const result = userSchema[field].validate(value); return result.valid ? null : result.errors[0].message; };
const handleSubmit = (e: FormEvent) => { e.preventDefault(); const newErrors: Record<string, string> = {};
Object.entries(formData).forEach(([field, value]) => { const error = validateField(field as keyof typeof userSchema, value); if (error) newErrors[field] = error; });
if (Object.keys(newErrors).length === 0) { console.log('Submitting:', formData); } else { setErrors(newErrors); } };
return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Username" onChange={e => setFormData(prev => ({ ...prev, username: e.target.value }))} /> {errors.username && <span>{errors.username}</span>} <button type="submit">Register</button> </form> ); } ```
Express API validation
```ts import express from 'express'; import { v } from 'isovalid';
const app = express(); app.use(express.json());
const productSchema = { name: v.string().min(3).max(100), price: v.number().min(0), category: v.string().custom(value => ['electronics', 'books', 'clothing'].includes(value) ? null : 'Invalid category' ) };
app.post('/api/products', (req, res) => { const errors = Object.entries(productSchema) .map(([field, schema]) => ({ field, result: schema.validate(req.body[field]) })) .filter(({ result }) => !result.valid) .map(({ field, result }) => ({ field, message: result.errors[0].message }));
if (errors.length > 0) { return res.status(400).json({ errors }); }
res.status(201).json(req.body); }); ```
Notice the custom validator in that second example. It takes the value and returns either null for valid, or a string describing what is wrong. That is the whole extension point, and it is enough for the rules that are specific to your domain: a category that has to exist, a discount that cannot exceed a price, an SKU that has to match a house format.
The payoff arrives when you pull productSchema out into a module both sides import. The browser then enforces exactly what the server enforces, and the answer to "why was this rejected?" lives in one file.
What IsoValid does not do yet
Being honest about the edges saves you an afternoon. At 1.0.4 the library ships two schema types: strings and numbers. There is no object or array schema yet, which is why both examples above describe a record as a plain object of field names to schemas and validate it field by field, rather than calling validate once on the whole payload. For flat forms and flat request bodies that is barely a difference. For deeply nested payloads it is a real one.
Validation is also synchronous, so a rule that needs a database round trip, such as checking that a username is not already taken, has to live outside the schema for now. And because errors are produced by the built-in rules, the message text is what the library gives you unless you supply a custom validator that returns your own wording.
None of this makes it the wrong tool. It makes it a tool with a shape worth knowing before you commit to it.
Best practices
- Reuse schemas. Define them once and share them across frontend and backend.
- Lean on the types. Let TypeScript's inference do the work rather than restating shapes by hand.
- Build schemas at module scope, not inside a request handler or a render. A schema is immutable once configured, so constructing it per request is work you pay for every time and never need to.
- Treat `valid` as the gate. Reading
errorson a passing result, or trusting data before checking the flag, is how validation quietly stops being validation.
Roadmap
- Array schema type
- Object schema type with nested validation
- Custom error message templates
- Async validation support
- Integration with popular form libraries
- Schema composition and inheritance
The first two are the ones that change the library's character, because together they turn field-by-field checking into validating a whole payload in a single call.
Is IsoValid right for your project?
It fits when you have a TypeScript codebase on both ends, mostly flat forms and request bodies, and you are tired of the client and server disagreeing about the rules. It fits especially well when bundle size is something you actually watch, since there are no transitive dependencies to audit and nothing to tree-shake around.
Reach for something larger when you need deep nested schemas, discriminated unions, async rules, or inferred static types derived from the schema itself. Those are mature features in the bigger validation libraries, and there is no prize for using a smaller one that does not do what you need. IsoValid is for the common case, kept small on purpose.
Getting started
IsoValid is open source and welcomes contributions.
