zod
zod is typeScript-first schema validation with static type inference.
Zova encapsulates zod and provides an enhanced version of z object.
Basic usage
Create a simple string schema.
const name = z.string();Specify as optional.
const name = z.string().optional();Set default value.
const name = z.string().optional().default('');Common types
string.
const name = z.string();number.
const age = z.number();boolean.
const bRead = z.boolean();bigint.
const num = z.bigint();date.
const birthday = z.date();object.
const user = z.object({
name: z.string().optional(),
age: z.number().optional(),
});Enhanced functionality
1. Coercion
Automatically perform type coercion using the schema generated by z. Because the Params and Query obtained from the route path are of string type by default, they need to be coerced to the actual target type.
2. boolean coercion
z performs special processing on boolean, coercing the strings 'false', 'undefined', 'null' or '0' to false
3. Support json object
We can pass json object in Query. For example, we define a user object in Query.
export const QuerySchema = z.object({
user: z
.object({
name: z.string(),
age: z.number(),
})
.optional(),
});The value of the user object can be obtained directly in render.
export class RenderCardHeader {
render() {
return (
<div>
<div>name: {this.$query.user?.name}</div>
<div>age: {this.$query.user?.age}</div>
</div>
);
}
}4. Support array object
We can pass array object in Query. For example, we define a colors array in Query.
export const QuerySchema = z.object({
colors: z.array(z.string()).optional(),
});The value of the colors array can be obtained directly in render.
export class RenderCardHeader {
render() {
return (
<div>
<div>colors: {this.$query.colors?.join(',')}</div>
<div>length: {this.$query.colors?.length}</div>
</div>
);
}
}