How to make client-side validation with default values? #275
-
I have some enum GenderType {
FEMALE = 'female',
MALE = 'male',
UNKNOWN = 'unknown',
}
const UserSchema = Type.Object({
id: Type.Number(),
gender: Type.Enum(GenderType, { default: GenderType.UNKNOWN }),
}) Something like that when correct value: const result = validate(UserSchema, { id: 1, gender: 'incorrect' })
console.log(result) // { id: 1, gender: "unknown" }
const result = validate(UserSchema, { id: 2, gender: null })
console.log(result) // { id: 1, gender: "unknown" } Something like that when value with error: const result = validate(UserSchema, { id: "string instead number", gender: 'male' })
// undefined | null | ValueError | throw Exception |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
@whalemare Hi, I have actually just pushed a patch / fix for this on Validation & Default ValuesTypeBox doesn't provide functionality to create default values during validation (either the data is correct or it's not). But if you are using Ajv, you can use useDefaults to automatically set Value.Create() & Value.Cast()As noted, while TypeBox doesn't provide a mechanism to automatically create default values for schemas specifically on validate, it does however provide a mechanism to transform a value into something that matches the expected type. See examples below import { Value } from '@sinclair/typebox/value'
enum GenderType {
FEMALE = 'female',
MALE = 'male',
UNKNOWN = 'unknown',
}
const UserSchema = Type.Object({
id: Type.Number(),
gender: Type.Enum(GenderType, { default: GenderType.UNKNOWN }),
})
const user0 = Value.Create(UserSchema)
// > { id: 0, gender: 'unknown' }
const user1 = Value.Cast(UserSchema, { id: 42 })
// > { id: 42, gender: 'unknown' })
const user2 = Value.Cast(UserSchema, { gender: 'female' })
// > { id: 0, gender: 'female' }) The If building client / server functionality, it is recommended to use Hope this helps! |
Beta Was this translation helpful? Give feedback.
@whalemare Hi, I have actually just pushed a patch / fix for this on
@sinclair/typebox@0.25.3
so information below relates to this version (and above)Validation & Default Values
TypeBox doesn't provide functionality to create default values during validation (either the data is correct or it's not). But if you are using Ajv, you can use useDefaults to automatically set
default
values if certain properties happen to be missing. This will need to be configured on the AJV object. Refer to the Ajv documentation for more information.Value.Create() & Value.Cast()
As noted, while TypeBox doesn't provide a mechanism to automatically create default values for schemas specifically on validate, it…