zod-forms
v1.0.2
Published
Strongly-typed headless forms for react with zod schemas.
Downloads
6
Readme
zod-forms
Zod Forms is a library for building forms in React using Zod for validation.
Usage
To use zod-forms
you need to create a form schema using Zod. The schema is a plain object with keys corresponding to the form fields and values corresponding to the validation rules. For example:
import z from 'zod';
export const demoSchema = z.object({
name: z
.string()
.nonempty('Name is required')
.min(2, {message: 'Must be 2 or more characters long'}),
age: z.number(),
});
For more information on Zod validation rules see the Zod documentation.
You can then use the useZodForm
hook to create a form component.
Here is a simple example:
import React from 'react';
import {useZodForm} from 'zod-forms';
import {demoSchema} from './DemoSchema';
export function TestComponent() {
const {Form} = useZodForm(demoSchema);
return (
<div>
<Form.Fields.name.Input>
<input placeholder="Your Name" />
</Form.Fields.name.Input>
<Form.Fields.age.Input>
<input placeholder="Your Age" />
</Form.Fields.age.Input>
</div>
);
}