{"id":13847411,"url":"https://github.com/anigenero/react-class-validator","last_synced_at":"2025-07-12T09:31:55.530Z","repository":{"id":40242874,"uuid":"263066464","full_name":"anigenero/react-class-validator","owner":"anigenero","description":"React hook for validating forms with class-validator","archived":false,"fork":false,"pushed_at":"2023-10-12T18:11:55.000Z","size":1635,"stargazers_count":13,"open_issues_count":6,"forks_count":5,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-11-08T05:32:17.219Z","etag":null,"topics":["class-validator","formik-validation","react","typescript","validation","validator"],"latest_commit_sha":null,"homepage":"","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/anigenero.png","metadata":{"files":{"readme":"README.md","changelog":null,"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}},"created_at":"2020-05-11T14:28:45.000Z","updated_at":"2024-07-11T06:02:20.000Z","dependencies_parsed_at":"2024-01-15T20:50:05.669Z","dependency_job_id":"b4a6f4b9-ba1d-4fbf-96ee-a5e1578fba6a","html_url":"https://github.com/anigenero/react-class-validator","commit_stats":{"total_commits":47,"total_committers":8,"mean_commits":5.875,"dds":0.6595744680851063,"last_synced_commit":"8ae4715df53be4db83bfb7d5b4cd6daaf6a0c8b7"},"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anigenero%2Freact-class-validator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anigenero%2Freact-class-validator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anigenero%2Freact-class-validator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anigenero%2Freact-class-validator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/anigenero","download_url":"https://codeload.github.com/anigenero/react-class-validator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225812895,"owners_count":17528083,"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":["class-validator","formik-validation","react","typescript","validation","validator"],"created_at":"2024-08-04T18:01:19.338Z","updated_at":"2024-11-21T22:30:20.616Z","avatar_url":"https://github.com/anigenero.png","language":"TypeScript","readme":"# react-class-validator\nEasy-to-use React hook for validating forms with the [class-validator](https://github.com/typestack/class-validator) library.\n\n[![Build Status](https://github.com/anigenero/react-class-validator/actions/workflows/build.yml/badge.svg)](https://github.com/anigenero/react-class-validator/actions/workflows/build.yml)\n[![codecov](https://codecov.io/gh/anigenero/react-class-validator/branch/master/graph/badge.svg)](https://codecov.io/gh/anigenero/react-class-validator)\n\n## Installation\n\n```bash\nnpm install --save react-class-validator\n```\n\n```typescript jsx\n\nconst validatorOptions: ValidatorContextOptions = {\n    onErrorMessage: (error): string =\u003e {\n        // custom error message handling (localization, etc)\n    },\n    resultType: 'boolean' // default, can also be set to 'map'\n}\n\nrender((\n    \u003cValidatorProvider options={validatorOptions}\u003e\n        \u003cMyComponent /\u003e\n    \u003c/ValidatorProvider\u003e\n), document.getElementById('root'))\n```\n\n## Default onErrorMessage behavior\nThe default behavior is to flatten all error constraints for each attribute.\n```typescript\nconst getDefaultContextOptions = (): ValidatorContextOptions =\u003e ({\n    onErrorMessage: (error) =\u003e Object.keys(error.constraints).map((key) =\u003e error.constraints[key])\n});\n```\n\n### react-intl\nWhen using libraries such as [react-intl](https://github.com/formatjs/formatjs), you don't have to modify the existing \n`onErrorMessage` handler. Decorators are handled at source load, so you only need to include the `intl.formatMessage` in your message definition.\n\n```typescript\nclass Person {\n\n    @IsEmail({}, {\n        message: intl.formatMessage(defineMessage({defaultMessage: 'Invalid email'}))\n    })\n    @IsNotEmpty({\n        message: intl.formatMessage(defineMessage({defaultMessage: 'Email cannot be empty'}))\n    })\n    public email: string;\n    \n}\n\n```\n\n## Usage\n\nCreate a class using validation decorators from `class-validator`.\n\n```typescript\nimport { IsNotEmpty } from \"class-validator\";\n\nclass LoginValidation {\n\n    @IsNotEmpty({\n        message: 'username cannot be empty'\n    })\n    public username: string;\n\n    @IsNotEmpty({\n        message: 'password cannot be empty'\n    })\n    public password: string;\n\n}\n```\n\nSet up your form component to validate using your validation class.  \n\n```typescript jsx\nconst MyComponent = () =\u003e {\n\n    const [username, setUsername] = useState('');\n    const [password, setPassword] = useState('');\n\n    const [validate, errors] = useValidation(LoginValidation);\n\n    return (\n        \u003cform onSubmit={async (evt) =\u003e {\n\n            evt.preventDefault();\n\n            // `validate` will return true if the submission is valid\n            if (await validate({username, password})) {\n                // ... handle valid submission\n            }\n\n        }}\u003e\n\n            {/* use a filter so that the onBlur function will only validate username */}\n            \u003cinput value={username} onChange={({target: {value}}) =\u003e setUsername(value)}\n                onBlur={() =\u003e validate({username}, ['username'])}/\u003e\n\n            {/* show error */}\n            {errors.username \u0026\u0026 (\n                \u003cdiv className=\"error\"\u003e\n                    {errors.username.map((message) =\u003e \u003cstrong\u003emessage\u003c/strong\u003e)}\n                \u003c/div\u003e\n            )}\n\n        \u003c/form\u003e\n    );\n\n};\n```\n\n## Usage With Formik\n\n`react-class-validator` easily integrates with [Formik](https://formik.org/). You can simply use the `validate` \nfunction returned from `useValidation`, so long as the Formik fields are named the same as the keys in your validation \nclass. Individual fields will have to be validated with `onBlur` functionality.\n\n### Formik error messages\n\nTo display error messages without custom handling, messages will need to be outputted as a map upon validation. \nDo this by overriding the default `resultType` (you can also do this at the component-level).\n\n```typescript\nconst options: ValidatorContextOptions = {\n    resultType: 'map'\n};\n```\n\nThen you can simply integrate with the default Formik flow.\n\n```typescript jsx\nexport const Login: FunctionComponent = () =\u003e {\n\n    const [validate] = useValidation(LoginValidation);\n\n    return (\n        \u003cFormik initialValues={{username: '', password: ''}}\n                validateOnBlur\n                validateOnChange\n                validate={validate}\u003e\n            {({values, touched, errors, handleChange, handleBlur}) =\u003e (\n                \u003cForm\u003e\n                    \n                    \u003clabel htmlFor=\"username\"\u003eUsername\u003c/label\u003e\n                    \u003cField id=\"username\" name=\"username\" placeholder=\"Username\" /\u003e\n\n                    {errors.username \u0026\u0026 touched.username ? (\n                        \u003cdiv\u003e{errors.username}\u003c/div\u003e\n                    ) : null}\n                    \n                    {/* other fields */}\n                    \n                    \u003cbutton type=\"submit\"\u003e\n                        Submit\n                    \u003c/button\u003e\n                    \n                \u003c/Form\u003e\n            )}\n        \u003c/Formik\u003e\n    );\n};\n```\n\n## Contributors\nLibrary built and maintained by [Robin Schultz](http://anigenero.com)\n\nIf you would like to contribute (aka buy me a beer), you can send funds via PayPal at the link below.\n\n[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick\u0026hosted_button_id=SLT7SZ2XFNEUQ)\n","funding_links":["https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick\u0026hosted_button_id=SLT7SZ2XFNEUQ"],"categories":["TypeScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanigenero%2Freact-class-validator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fanigenero%2Freact-class-validator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanigenero%2Freact-class-validator/lists"}