{"id":13742006,"url":"https://github.com/luoanb/hook-form-react","last_synced_at":"2025-05-08T22:33:01.216Z","repository":{"id":226644426,"uuid":"769271896","full_name":"luoanb/hook-form-react","owner":"luoanb","description":"This library is a lightweight, dependency-free solution for form validation and submission designed specifically for React applications.  该库是一个专为 React 应用设计的轻量级、无依赖的表单验证和提交解决方案。","archived":false,"fork":false,"pushed_at":"2024-03-31T17:08:32.000Z","size":437,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-07-06T02:23:30.055Z","etag":null,"topics":["form","forms-validation","hook","library","mui","nextui","react","react-hook-form","typedoc","typescript","validation"],"latest_commit_sha":null,"homepage":"https://luoanb.github.io/hook-form-react/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/luoanb.png","metadata":{"files":{"readme":"README.en.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-03-08T17:41:31.000Z","updated_at":"2024-06-11T19:08:49.000Z","dependencies_parsed_at":"2024-03-14T18:01:33.933Z","dependency_job_id":"c9900a93-a426-4db2-b104-521735f3f3df","html_url":"https://github.com/luoanb/hook-form-react","commit_stats":null,"previous_names":["luoanb/hook-form-react"],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luoanb%2Fhook-form-react","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luoanb%2Fhook-form-react/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luoanb%2Fhook-form-react/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luoanb%2Fhook-form-react/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/luoanb","download_url":"https://codeload.github.com/luoanb/hook-form-react/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":213764342,"owners_count":15635169,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["form","forms-validation","hook","library","mui","nextui","react","react-hook-form","typedoc","typescript","validation"],"created_at":"2024-08-03T04:01:05.166Z","updated_at":"2024-08-03T04:05:05.686Z","avatar_url":"https://github.com/luoanb.png","language":"TypeScript","readme":"# Hook Form React\n\nThis library is a lightweight, dependency-free solution for form validation and submission designed specifically for React applications.The following component libraries have been adapted: `Next UI`, `Ant Design`, and `MUI`.\n\n**It is recommended to view the examples directly**: The updates here are the most timely and the recommended way to use.\n\nEnglish | [中文](./README.md) | [API](https://luoanb.github.io/hook-form-react/) | [GitHub](https://github.com/luoanb/hook-form-react) | [Example:Stackblitz](https://stackblitz.com/~/github.com/luoanb/hook-form-react-example) | [Example:GitHub](https://github.com/luoanb/hook-form-react-example)\n\nDeveloped using React Hooks and TypeScript, it aims to provide a simple, efficient, and extensible way to handle form validation and submission, whether in simple or complex form scenarios. The design philosophy of this library emphasizes compatibility and extensibility, with the principle of supporting developers to achieve the richest functionality with the least code possible. It does not bind to any UI component library, thereby supporting all React component libraries.\n\n## Features\n\n- **Zero Dependencies**: Avoids project bloat and compatibility issues that may arise from external dependencies.\n- **Highly Extensible**: Easily adaptable to various validation rules and form scenarios to meet different requirements.\n- **TypeScript Support**: Takes full advantage of TypeScript's type checking to enhance code readability and maintainability.\n- **Universality**: Compatible with all UI component libraries, providing a unified form processing solution for React developers.\n- **Documentation Support**: Utilizes TypeDoc to generate comprehensive documentation, helping developers better understand and use the features of the library.\n- **Flexible Packaging Support**: Uses Rollup for packaging, supporting UMD, CommonJS, and ES module formats to adapt to different usage scenarios and environments.\n\n## Installation\n\n```shell\n# pnpm\npnpm add hook-form-react\n\n# yarn\nyarn add hook-form-react\n\n# npm\nnpm i hook-form-react\n```\n\n## Usage\n\n### Basic usage\n\nIn principle, it can adapt to all React component libraries, although this slightly increases the amount of code.\n\n```typescript\n// Basic usage: In principle, it can adapt to all React component libraries, although this slightly increases the amount of code.\nimport { useAttr, useFormData } from 'hook-form-react'\n// Using NextUI\nimport { Button, Input, Link } from '@nextui-org/react'\n\nconst Example = () =\u003e {\n  const formData = useFormData(\n    { password: '', username: '' }, // Default data\n    {\n      // Validation rules for password\n      password: [\n        {\n          execute: async (value) =\u003e !!value,\n          msg: 'Password cannot be empty'\n        }\n      ],\n      // Validation rules for username\n      username: [\n        {\n          execute: async (value) =\u003e !!value,\n          msg: 'Username cannot be empty'\n        }\n      ]\n    }\n  )\n\n  // Submission\n  const submit = async () =\u003e {\n    // Validate all form fields\n    const isValid = await formData.doAllValidate()\n    console.log('submit:isValid: ', isValid)\n    if (isValid) {\n      // Validation successful\n      console.log('formValue:', formData.value)\n    }\n  }\n  return (\n    \u003cdiv\u003e\n      \u003cInput\n        placeholder=\"Please enter your username\"\n        className=\"mb-4 mt-10 login-input text-sm\"\n        isInvalid={formData.errors.username?.isInvalid} // Bind error state\n        errorMessage={formData.errors.username?.msg} // Bind error message\n        value={formData.value.username} // Bind value\n        onChange={(e) =\u003e formData.pushValue('username', e.target.value)} // Handle onChange\n      \u003e\u003c/Input\u003e\n      \u003cInput\n        autoComplete=\"new-password\"\n        type=\"password\"\n        placeholder=\"Please enter your password\"\n        value={formData.value.password}\n        isInvalid={formData.errors.password?.isInvalid}\n        errorMessage={formData.errors.password?.msg}\n        onChange={(e) =\u003e formData.pushValue('password', e.target.value)}\n      \u003e\u003c/Input\u003e\n      \u003cButton onClick={submit}\u003eLogin\u003c/Button\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n### Advanced Usage\n\nProviding Utility Tools for Faster Development Without Losing Customizability\n\n```typescript\n// Advanced Usage: Providing Utility Tools for Faster Development Without Losing Customizability\n\nimport { Button, Input } from '@nextui-org/react'\nimport { useAttr, useFormData, Verifications } from 'hook-form-react'\n\nexport const Example = () =\u003e {\n  const formData = useFormData(\n    { password: '', username: '' },\n    {\n      // Supports multiple validations\n      password: [\n        // Built-in validator for required field validation\n        // Developers can also add other validation rules in their projects, see the developer documentation for details (to be added)\n        Verifications.required(),\n        // Built-in validator for password validation\n        Verifications.password()\n      ],\n      username: [\n        // Built-in validator for required field validation + custom message\n        Verifications.required('Username cannot be empty'),\n        // Built-in validator for username validation\n        Verifications.username()\n      ]\n    }\n  )\n\n  // Use component to quickly bind hooks\n  const attr = useAttr(formData)\n\n  const submit = async () =\u003e {\n    const isValid = await formData.doAllValidate()\n    console.log('submit:isValid: ', isValid)\n    if (isValid) {\n      console.log('formValue', formData.value)\n    }\n  }\n\n  return (\n    \u003cdiv className=\"p-10 pt-18 pb-0 flex-col\"\u003e\n      \u003cInput\n        placeholder=\"Please enter your username\"\n        // Comment out the original binding logic\n        // value={formData.value.username}\n        // onChange={(e) =\u003e formData.pushValue('username', e.target.value)}\n        // isInvalid={formData.errors.username?.isInvalid}\n        // errorMessage={formData.errors.username?.msg}\n\n        // Replace with quick binding\n        // NextUI.N_Input is specifically adapted for [NextUI.Input], other components are being supplemented\n        // Developers can also add support for third-party components in their projects, see the developer documentation for details (to be added)\n        {...attr('username', attr.NextUI.N_Input)}\n      \u003e\u003c/Input\u003e\n      \u003cInput\n        autoComplete=\"new-password\"\n        type=\"password\"\n        placeholder=\"Please enter your password\"\n        {...attr('password', attr.NextUI.N_Input)}\n        // value={formData.value.password}\n        // isInvalid={formData.errors.password?.isInvalid}\n        // errorMessage={formData.errors.password?.msg}\n        // onChange={(e) =\u003e formData.pushValue('password', e.target.value)}\n      \u003e\u003c/Input\u003e\n\n      \u003cButton onClick={submit}\u003eLogin\u003c/Button\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n### Nested Object Forms\n\nIntroducing a new hook `useSubFormData` for handling nested forms, which, in principle, can handle an arbitrary number of object nesting layers (i.e., infinite nesting).\n\n```ts\n// useSubFormData\nconst value10Form = useSubFormData(formData.formData, 'value10', {\n  haha: [Verifications.required(), Verifications.email()]\n})\n\n/**\n * This is required for binding to form components of nested objects.\n */\nconst attrValue10 = useAttr(value10Form)\n\n// Submit\nconst submit = async () =\u003e {\n  const isValid = await formData.doAllValidate()\n  // Nested forms need to be validated separately\n  const isValidValue10 = await value10Form.doAllValidate()\n  console.log('submit:isValid: ', isValid, isValidValue10)\n  if (isValid \u0026\u0026 isValidValue10) {\n    // The top-level form can access all values\n    console.log('formValue', formData.value)\n  }\n}\n\n// Reset\nconst reset = () =\u003e {\n  formData.reset()\n  // Error states need to be reset separately\n  value10Form.formErrors.reset()\n}\n```\n\n## Version Notes\n\n- **Future Plans for Next Versions**\n\n- **Next Version Plan**\n\n  1. **Documentation Optimization**: We will improve the accessibility of the documentation, including usage examples for each API, as well as handling details during the use of various component libraries.\n  2. **Stability Optimization**: Optimize the stability and experience of some component libraries.\n  3. **Support for Mobile/Mini Program Component Libraries**: `hook-form-react` is modular and lightweight (around 10k), suitable for use in mini programs. We will consider adapting to the `Taro` mini program component library in the future.\n  4. **Improving Development Documentation**: Based on the pluggable design principle, it is simple to add adaptations for third-party component libraries and custom validations in `hook-form-react`. We will continue to improve the development documentation to help developers customize the use of `hook-form-react` based on project needs.\n\n- **v2.3.0**\n\n  1. **MUI Components**: Completed the adaptation of the `MUI` component library. Please see the [example](https://stackblitz.com/~/github.com/luoanb/hook-form-react-example) for usage.\n\n- **v2.2.0**\n\n  1. **Antd UI**: Form components have been adapted. As of the current version, we have adapted two component libraries, `Next UI` and `Antd`. To import Antd components, use `import { Antd_5 } from 'hook-form-react/Antd_5'`. All adaptations for Antd are included here and isolated from the core library. For usage examples, please refer to [Example: Stackblitz](https://stackblitz.com/~/github.com/luoanb/).\n\n- **v2.1.0**\n\n  1. Fixed an issue where the latest form data could not be obtained when assigning values and validating immediately (a bug caused by the asynchronous execution of React.useState).\n     Added two functions `doValidateImme` and `doAllValidateImme`. When issues are found using `doValidate` or `doAllValidate`, replace them with the corresponding new functions. Principally, it is recommended to use `doValidate` and `doAllValidate` first.\n\n- **v2.0.2**\n\n  1. Custom validation rules, `execute?: (value: V, content: any) =\u003e Promise\u003cboolean\u003e`, added a `content` parameter for accessing form context data.\n\n- **v2.0.0**\n\n  1. Added support for nested object forms. For more details, see [Stackblitz](https://stackblitz.com/~/github.com/luoanb/hook-form-react-example).\n  2. Added a Stackblitz example project (requires VPN for access).\n\n- **v1.0.0 (Official Release)**\n\n  1. Refactored the validation rule implementation class for a friendlier usage experience, and added several common validation rules [All common validation rules](https://luoanb.github.io/hook-form-react/classes/Verifications.html). The validation rules have not been fully tested; issues are welcome to be reported.\n  2. **NextUI Components**: All forms have now been adapted [All adapted components](https://luoanb.github.io/hook-form-react/classes/NextUI_2_2.html) (any omissions will be updated, @manual dog, hehe)\n  3. Fixed inaccurate type declarations.\n  4. Added test projects for functionality verification.\n\n- **v0.5.x (Core Implementation Preview)**\n\n  1. The core framework has been implemented, offering a smooth user experience, and can be directly used [see advanced usage]() below.\n  2. Overall good extensibility, with component library related code and core form code being completely isolated, laying the foundation for future support of different component libraries.\n  3. Complete control over form data state and form error state, allowing for customization according to business logic.\n  4. Validation rules are also uniformly implemented, making extension and customization convenient.\n  5. Zero dependencies, purely hooks-based.\n\n## Component Library Support\n\n- **90 Points**: NextUI provides a good experience, and issues are promptly fixed (also in use by ourselves).\n\n- **80 Points**: MUI, given its lack of support for form validation, using hook-form-react is still a good choice. At least compared to react-hook-form, it doesn't have a bunch of complex concepts, right?\n\n- **80 Points**: Antd components have a good native form experience, prefer to choose their own forms (subsequent adaptations mainly consider dual component library scenarios).\n\n- **60 Points**: ......\n\n## API Reference\n\nThis section should provide detailed information about the hooks, functions, their parameters, return types, and usage examples offered by the library, enabling developers to quickly get started and effectively utilize the library's features.\n\n[API](https://luoanb.github.io/hook-form-react/)\n\n## Contribution Guidelines\n\nWe welcome and encourage community members to contribute to this project, whether through submitting bug reports, feature requests, or directly contributing code. Please refer to our contribution guidelines for more information.\n\n## License\n\nThis project is licensed under the MIT License, details of which can be found in the [LICENSE](./LICENSE) file.\n","funding_links":[],"categories":["Code Design"],"sub_categories":["Form Logic"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluoanb%2Fhook-form-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fluoanb%2Fhook-form-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluoanb%2Fhook-form-react/lists"}