@othree.io/auditor
v5.0.0
Published
A functional validation library built on Zod that returns Optional<T> instead of throwing exceptions
Downloads
166
Maintainers
Readme
@othree.io/auditor
A functional validation library built on Zod. Validation results are returned as Optional<T> from @othree.io/optional, so invalid input never throws — you get either a filled Optional with the parsed value or an empty one carrying a ValidationError.
Install
npm install @othree.io/auditorPeer dependencies:
npm install zod @othree.io/optionalUsage
zodValidate
Creates a curried validation function from any Zod schema. Returns Optional<T> — filled on success, empty with a ValidationError on failure.
import { z } from 'zod'
import { zodValidate } from '@othree.io/auditor'
const UserSchema = z.object({
name: z.string().min(1),
age: z.number().int().nonnegative(),
}).strict()
type User = z.infer<typeof UserSchema>
const validateUser = zodValidate({ constraints: UserSchema })
const result = validateUser({ name: 'Alice', age: 30 })
if (result.isPresent) {
console.log(result.get()) // { name: 'Alice', age: 30 }
} else {
console.log(result.getError().errors)
// e.g. { name: ['String must contain at least 1 character(s)'] }
}Built-in constraints
The library exports common string constraints ready to use with zodValidate:
| Constraint | Description |
|------------------|------------------------------------------------------|
| NonEmptyString | Trims whitespace, requires at least 1 character |
| CountryISOCode | Two uppercase letters (e.g. US, MX) |
| LanguageCode | Two lowercase letters (e.g. en, es) |
import { zodValidate, NonEmptyString, CountryISOCode, LanguageCode } from '@othree.io/auditor'
zodValidate({ constraints: NonEmptyString })(' hello ') // Optional('hello')
zodValidate({ constraints: CountryISOCode })('US') // Optional('US')
zodValidate({ constraints: LanguageCode })('es') // Optional('es')
zodValidate({ constraints: LanguageCode })('BAD') // Empty(ValidationError)toValidationError
Converts a Zod ZodError into a ValidationError with per-field error messages. Used internally by zodValidate, but available if you need to work with Zod errors directly.
import { toValidationError } from '@othree.io/auditor'
import { z } from 'zod'
const result = z.string().min(1).safeParse('')
if (!result.success) {
const error = toValidationError(result.error)
console.log(error.errors) // { input: ['String must contain at least 1 character(s)'] }
}ValidationError
When validation fails, the Optional carries a ValidationError with per-field error messages:
import { ValidationError } from '@othree.io/auditor'
const error = new ValidationError({
email: ['Required'],
age: ['Expected number, received string'],
})
error.name // 'ValidationError'
error.errors // { email: ['Required'], age: ['Expected number, received string'] }Scripts
npm test # run tests with 100% coverage threshold
npm run build # compile TypeScript to lib/License
ISC
