Closed askareija closed 2 months ago
@askareija Hi,
TypeBox doesn't have cross field validation as it's not well represented in the Json Schema specification. However you can reimplement this type in the following way to make use of TypeScript discriminated unions (which is supported in TypeBox)
import { Type as t, Static } from '@sinclair/typebox'
export type AuthRequestVerificationType = Static<typeof AuthRequestVerificationType>
export const AuthRequestVerificationType = t.Union([
t.Object({
sendMethod: t.Literal('email'), // discriminator
contact: t.String({ format: 'email' })
}),
t.Object({
sendMethod: t.Literal('whatsapp'), // discriminator
contact: t.String({ minLength: 8 })
}),
])
Hope this helps S
Just as follow on addendum, for your particular case, the specification does support conditional schematics which would work for your particular use case...
import { Type, Static } from '@sinclair/typebox'
export const T = Type.Object({
x: Type.Union([
Type.Literal(1),
Type.Literal(2),
]),
}, {
if: Type.Object({ x: Type.Literal(1) }),
then: Type.Object({ y: Type.Literal(3) })
})
// if x === 1 expect { x: 1, y: '...' }
// if x === 2 expect { x: 2 }
However the TypeBox compiler infrastructure doesn't currently support these kind of schematics as there are difficulties reconciling the appropriate static type (although the above schematic is supported in Ajv and other standard validators). As Elysia is backed by the TypeBox TypeCompiler, the recommendation is to use the Discriminated Union type above.
Cheers S
Ah i see, thanks! i'll try this
Hi!, i have a question. I'm using elysia and i know that elysia using typebox for validation. I have validation code like this:
Is there a way i can validate if the
sendMethod
field is email, then contact field validation must bet.String
with email format, else if whatsapp then the validation ist.String
with minLength of 8?Thanks