Example
Add zod validation and defaults to your instant schema by wrapping the field with the addZod
function. This example shows a few different zod examples.
makeLinkRequired
is a helper function that makes a link field required with a custom zod error message.
import { addZod, makeLinkRequired } from 'instantdb-react-ui';
export enum USER_CATEGORY { Free = 'Free', Pro = 'Pro', }
const _schema = i.schema({
entities: {
persons: i.entity({
name: addZod(i.string().unique().indexed(),
z.string().min(3).max(25)),
email: addZod(i.string().unique().indexed(),
z.string().email().min(5).max(100)),
date: addZod(i.date().indexed(),
z.number().min(new Date('2020-01-01').getTime()).default(Date.now)),
category: addZod(i.string(),
z.nativeEnum(USER_CATEGORY)),
admin: addZod(i.boolean(),
z.boolean().default(false)),
}),
},
});
// These entities are not defined to keep this example small, but you can see how to make links required
makeLinkRequired(_schema.entities.items.links.owner, 'Please select at least one owner');
makeLinkRequired(_schema.entities.items.links.room, 'Please select a room');
InstantDB uses number | string
for dates, which is why we use z.number() for validation and a number value for the default.
Defaults
Using zod is optional! Without it, the form will automatically use a default zod validator depending on the instantdb type.
Showing errors
Error message values are passed to the UI components as a prop inside the form.Field
component.
field.state.meta.errors
is an array of zod errors that you can use to show custom error messages.
getErrorMessageForField
is a helper function that returns a concatenated string of all the error messages.
Responses are generated using AI and may contain mistakes.