@schemasjs/validator
v2.0.0
Published
An opinionated type validator API indpendent from schema validators like Zod, Valibot, etc
Downloads
50
Maintainers
Readme
@SchemasJS/validator
If you love type validators like Zod or Valibot, probably you load a ton of logic inside schemas. If suddenly you wanted to swap from one type validator to another, the migration would be a pain. This package try to minimize this problem.
Validator is an opinionated API to work with your favourites schemas coming from Zod or Valibot. You can use your preferred schemas in and if you need to swap to another it won't be a problem.
At this moment it is only supported Zod and Valibot.
How to use Validator
In your schemas file, import the proper Validator that you need and create your validator for each schema.
// Zod import { z } from 'zod' import { ZodValidator } from '@schemasjs/validator' import { Uint8Schema as ZodUint8Schema, type Uint8 } from '@schemasjs/zod-numbers' const Uint8Schema = new ZodValidator<Uint8>() const ZodEmailSchema = z.string().email() type Email = z.infer<typeof ZodEmailSchema> const EmailSchema = ZodValidator<Email>(ZodEmailSchema) // Valibot import * as v from 'valibot' import { ValibotValidator } from '@schemasjs/validator' import { Uint8Schema as ValibotUint8Schema, type Uint8 } from '@schemasjs/valibot-numbers' const Uint8Schema = ValibotValidator<Uint8>() const ValibotEmailSchema = v.pipe(v.string(), v.email()) type Email = v.InferInput<typeof ValibotEmailSchema> const EmailSchema = ValibotValidator<Email>(ValibotEmailSchema)
Then use it in your code instead your schemas, and that's all.
const myEmail = '[email protected]' console.log(EmailSchema.is(myEmail) ? 'Valid email' : 'Invalid email') // 'Valid email' const parsedEmail = EmailSchema.parse(myEmail) // '[email protected]' const parsed = EmailSchema.safeParse(myEmail) console.log(parsed.success ? parsed.data : parsed.errors) // '[email protected]'
Validator API
is: (data: any) => boolean
parse: (data: any) => T
safeParse: (data: any) => SafeParse<T>
It is a tiny API based on Zod API + is
Valibot function API.
safeParse
return
interface SafeParseSuccess<T> {
success: true
value: T
}
interface SafeParseFailure {
success: false
errors: string[]
}
export type SafeParse<T> = SafeParseSuccess<T> | SafeParseFailure