@odyssoft/zod-mui-forms
v1.0.28
Published
React form components built using Material UI with zod for validation
Downloads
291
Readme
@odyssoft/zod-mui-forms
Odyssoft zod mui forms package, built using Mui & storybook Create forms with automatic validation with ease, for use on both client and server components.
Installation
npm i @odyssoft/zod-mui-formsBasic Usage
Define a schema
Schema creation using zod is very straight forward as shown in the below example;
const mySchema = z.object({
name: z.string().min(3),
email: z.string().email(),
age: z.number().optional(),
})Of course there are many more complex use cases which you can find more information on by visiting the official zod documentation
Create a server action
Validation is handled automatically by the form before the action is called, so there is no need to safeParse the form data or guard against validation errors inside the action.
'use server'
import { ServerAction } from '@odyssoft/zod-mui-forms'
import { mySchema } from './mySchema'
export const myAction: ServerAction<typeof mySchema> = async (state) => {
// state.data is already validated — use it directly
const { name, email, birthday } = state.data
// Add your server logic here
return {}
}Create the react form
Next.js users: Form components must be marked with
'use client'since Next.js does not allow passing non-serializable values (such as Zod schemas) as props to client components from a server component.
'use client'
import { Form, FormError, Input, Submit } from '@odyssoft/zod-mui-forms'
import { z } from 'zod'
import { myAction } from './actions'
import { mySchema } from './schema'
export const MyForm = () => {
return (
<Form action={myAction} schema={mySchema}>
<FormError />
<Input label='Name' name='name' />
<Input label='Email' name='email' />
<Input label='Birthday' name='birthday' type='date' />
<Submit>Submit</Submit>
</Form>
)
}<FormError /> renders a general-purpose error alert at whatever position you place it among the form's children. It displays the top-level error string returned from your server action and renders nothing when there is no error.
To surface an error from your action, return an error string in the response:
export const myAction: ServerAction<typeof mySchema> = async (state) => {
try {
// Add your server logic here
return {}
} catch (e) {
return { error: 'Something went wrong. Please try again.' }
}
}