https://github.com/gbrogio/next-hook-form
A hook for form validation in Next.js & React
https://github.com/gbrogio/next-hook-form
form form-validation form-validation-react hooks nextjs react react-hooks
Last synced: about 1 month ago
JSON representation
A hook for form validation in Next.js & React
- Host: GitHub
- URL: https://github.com/gbrogio/next-hook-form
- Owner: gbrogio
- License: mit
- Created: 2024-08-18T13:50:06.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-08-18T14:07:40.000Z (over 1 year ago)
- Last Synced: 2025-10-10T04:24:05.927Z (5 months ago)
- Topics: form, form-validation, form-validation-react, hooks, nextjs, react, react-hooks
- Language: TypeScript
- Homepage: https://next-hook-form.vercel.app
- Size: 54.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# useForm Hook
The `useForm` is a custom hook for managing forms in React, with support for schema validation using the `zod` library.
## Installation
To use `useForm`, you need to have React and Zod installed in your project.
```sh
npm install next-hook-form zod
```
## Usage
Here is an example of how to use `useForm` in a React component:
```tsx
"use client";
import { useForm } from "@/hooks/next-hook-form";
import * as React from "react";
import { z } from "zod";
export default function Home() {
const { createRef, handleSubmit, isDirty, watch, isPending } = useForm({
schema: {
name: z.string().min(20),
name1: z.string().min(30),
terms: z.boolean().refine((v) => v, "Fill terms!"),
},
});
return (
{})} className="space-y-4">
Submit
);
}
```
## API
### `useForm`
```typescript
function useForm(opts: {
schema: T;
}): {
createRef: (
name: K,
dispareErrorOn?: "submit" | "change"
) => {
ref: React.RefObject;
name: K;
onChange: () => void;
};
handleSubmit: (
cb: (inputs: any, error: string | null) => Promise
) => (ev: React.FormEvent) => void;
isDirty: boolean;
watch: (
names: (keyof T)[]
) => { name: keyof T; value: string | boolean | null }[];
isPending: boolean;
error: string | null;
setError: (error: string | null, name?: keyof T) => void;
getValue: (name: keyof T) => string | boolean | null;
getInput: (name: keyof T) => HTMLInputElement | null;
};
```
#### Parameters
- `opts`: An object containing the validation schema.
#### Returns
- `createRef`: Creates a reference for an input field.
- `handleSubmit`: Handles form submission.
- `isDirty`: Indicates if any form field is dirty.
- `watch`: Watches the values of specified fields.
- `isPending`: Indicates if the form is in a pending state.
- `error`: Contains the current error message.
- `setError`: Sets an error message for a specific field or the entire form.
- `getValue`: Gets the value of a specific field.
- `getInput`: Gets the reference of a specific field.
## License
This project is licensed under the MIT License. See the `LICENSE` file for more details.