{"id":17932723,"url":"https://github.com/michallytek/class-transformer-validator","last_synced_at":"2025-04-04T18:08:45.163Z","repository":{"id":16970478,"uuid":"80755751","full_name":"MichalLytek/class-transformer-validator","owner":"MichalLytek","description":"A simple plugin for class-transformer and class-validator which combines them in a nice and programmer-friendly API.","archived":false,"fork":false,"pushed_at":"2023-01-11T22:27:35.000Z","size":298,"stargazers_count":200,"open_issues_count":14,"forks_count":19,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-10-28T21:04:58.195Z","etag":null,"topics":["javascript","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/MichalLytek.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}},"created_at":"2017-02-02T18:32:18.000Z","updated_at":"2024-07-03T02:19:23.000Z","dependencies_parsed_at":"2023-01-14T12:44:23.975Z","dependency_job_id":null,"html_url":"https://github.com/MichalLytek/class-transformer-validator","commit_stats":null,"previous_names":["19majkel94/class-transformer-validator"],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MichalLytek%2Fclass-transformer-validator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MichalLytek%2Fclass-transformer-validator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MichalLytek%2Fclass-transformer-validator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MichalLytek%2Fclass-transformer-validator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MichalLytek","download_url":"https://codeload.github.com/MichalLytek/class-transformer-validator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247226215,"owners_count":20904465,"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":["javascript","typescript","validation","validator"],"created_at":"2024-10-28T21:30:09.386Z","updated_at":"2025-04-04T18:08:45.144Z","avatar_url":"https://github.com/MichalLytek.png","language":"TypeScript","readme":"# class-transformer-validator\n\n[![npm version](https://badge.fury.io/js/class-transformer-validator.svg)](https://badge.fury.io/js/class-transformer-validator)\n[![Dependency Status](https://david-dm.org/MichalLytek/class-transformer-validator.svg)](https://david-dm.org/MichalLytek/class-transformer-validator)\n[![devDependency Status](https://david-dm.org/MichalLytek/class-transformer-validator/dev-status.svg)](https://david-dm.org/MichalLytek/class-transformer-validator#info=devDependencies)\n[![peerDependency Status](https://david-dm.org/MichalLytek/class-transformer-validator/peer-status.svg)](https://david-dm.org/MichalLytek/class-transformer-validator#info=devDependencies)\n\nA simple plugin for [class-transformer](https://github.com/typestack/class-transformer) and [class-validator](https://github.com/typestack/class-validator) which combines them in a nice and programmer-friendly API.\n\n## Installation\n\n#### Module installation\n\n`npm install class-transformer-validator --save`\n\n(or the short way):\n\n`npm i -S class-transformer-validator`\n\n#### Peer dependencies\n\nThis package is only a simple plugin/wrapper, so you have to install the required modules too because it can't work without them. See detailed installation instruction for the modules installation:\n\n- [class-transformer](https://github.com/typestack/class-transformer#installation)\n- [class-validator](https://github.com/typestack/class-validator#installation)\n\n## Usage\n\nThe usage of this module is very simple.\n\n```ts\nimport { IsEmail } from \"class-validator\";\nimport { transformAndValidate } from \"class-transformer-validator\";\n\n// declare the class using class-validator decorators\nclass User {\n  @IsEmail()\n  public email: string;\n\n  public hello(): string {\n    return \"World!\";\n  }\n}\n\n// then load the JSON string from any part of your app\nconst userJson: string = loadJsonFromSomething();\n\n// transform the JSON to class instance and validate it correctness\ntransformAndValidate(User, userJson)\n  .then((userObject: User) =\u003e {\n    // now you can access all your class prototype method\n    console.log(`Hello ${userObject.hello()}`); // prints \"Hello World!\" on console\n  })\n  .catch(err =\u003e {\n    // here you can handle error on transformation (invalid JSON)\n    // or validation error (e.g. invalid email property)\n    console.error(err);\n  });\n```\n\nYou can also transform and validate plain JS object (e.g. from express req.body). Using ES7 async/await syntax:\n\n```ts\nasync (req, res) =\u003e {\n  try {\n    // transform and validate request body\n    const userObject = await transformAndValidate(User, req.body);\n    // infered type of userObject is User, you can access all class prototype properties and methods\n  } catch (err) {\n    // your error handling\n    console.error(err);\n  }\n};\n```\n\nAnd since release `0.3.0` you can also pass array of objects - all of them will be validated using given class validation constraints:\n\n```ts\nasync (req, res) =\u003e {\n  try {\n    // transform and validate request body - array of User objects\n    const userObjects = await transformAndValidate(User, req.body);\n    userObjects.forEach(user =\u003e console.log(`Hello ${user.hello()}`));\n  } catch (err) {\n    // your error handling\n  }\n};\n```\n\n## API reference\n\n#### Function signatures\n\nThere is available the `transformAndValidate` function with three overloads:\n\n```ts\nfunction transformAndValidate\u003cT extends object\u003e(\n  classType: ClassType\u003cT\u003e,\n  jsonString: string,\n  options?: TransformValidationOptions,\n): Promise\u003cT | T[]\u003e;\n```\n\n```ts\nfunction transformAndValidate\u003cT extends object\u003e(\n  classType: ClassType\u003cT\u003e,\n  object: object,\n  options?: TransformValidationOptions,\n): Promise\u003cT\u003e;\n```\n\n```ts\nfunction transformAndValidate\u003cT extends object\u003e(\n  classType: ClassType\u003cT\u003e,\n  array: object[],\n  options?: TransformValidationOptions,\n): Promise\u003cT[]\u003e;\n```\n\nBe aware that if you validate json string, the return type is a `Promise` of `T` or `T[]` so you need to assert the returned type if you know the shape of json:\n\n```ts\nconst users = (await transformAndValidate(\n  User,\n  JSON.stringify([{ email: \"test@test.test\" }]),\n)) as User[];\n```\n\nOr you can just check the type in runtime using `Array.isArray` method.\n\n#### Synchronous transformation and validation\n\nIf you need sync validation, use `transformAndValidateSync` function instead (available since v0.4.0). It will synchronously return `T` or `T[]`, not a Promise.\n\n#### Parameters and types\n\n- `classType` - an class symbol, a constructor function which can be called with `new`\n\n```ts\ntype ClassType\u003cT\u003e = {\n  new (...args: any[]): T;\n};\n```\n\n- `jsonString` - a normal string containing JSON\n\n- `object` - plain JS object of type `object` (introduced in TypeScript 2.2), you will have compile-time error while trying to pass number, boolean, null or undefined but unfortunately run-time error when passing a function\n\n- `array` - array of plain JS objects like described above\n\n- `options` - optional options object, it has two optional properties\n\n```ts\ninterface TransformValidationOptions {\n  validator?: ValidatorOptions;\n  transformer?: ClassTransformOptions;\n}\n```\n\nYou can use it to pass options for `class-validator` ([more info](https://github.com/pleerock/class-validator/blob/master/src/validation/ValidatorOptions.ts)) and for `class-transformer` ([more info](https://github.com/pleerock/class-transformer/blob/master/src/ClassTransformOptions.ts)).\n\n## More info\n\nThe [class-transformer](https://github.com/pleerock/class-transformer) and [class-validator](https://github.com/pleerock/class-validator) are more powerful than it was showed in the simple usage sample, so go to their github page and check out they capabilities!\n\n## Release notes\n\n**0.9.1**\n\n- widen `class-transformer` peer dependency version range to `\u003e=0.2.3`\n- updated all dev dependencies\n\n**0.9.0**\n\n- bump `class-validator` peer dependency to version `\u003e=0.12.0`\n- updated TypeScript dependency to version `^3.9.5`\n- updated all dev dependencies\n\n**0.8.0**\n\n- updated `class-transformer` dependency to version `^0.2.3`\n- updated `class-validator` dependency to version `^0.10.1`\n- updated TypeScript dependency to version `^3.6.3`\n- built code is now emitted as ES2015 (dropped es5 support)\n- updated all dev dependencies\n\n**0.7.1**\n\n- updated `class-transformer` dependency to version `^0.2.0`\n\n**0.6.0**\n\n- updated `class-validator` dependency to version `^0.9.1`\n\n**0.5.0**\n\n- remove deprecated `TransformValdiationOptions` interface (typo)\n- updated `class-validator` dependency to version `^0.8.1` and `class-transformer` to `^0.1.9`\n\n**0.4.1**\n\n- fix `TransformValdiationOptions` interface name typo (deprecate in favour of `TransformValidationOptions`)\n\n**0.4.0**\n\n- added `transformAndValidateSync` function for synchronous validation\n- changed return type for JSON's transform and validation to `Promise` of `T` or `T[]`\n- updated `class-validator` dependency to version `^0.7.2` and `class-transformer` to `^0.1.7`\n\n**0.3.0**\n\n- added support for transform and validate array of objects given class\n- updated `class-validator` dependency to version `^0.7.1`\n\n**0.2.0**\n\n- changed object parameter type declaration to `object` (introduced in TS 2.2)\n- throwing error when passed array, undefined or null\n\n**0.1.1**\n\n- changed throwing error (rejecting promise) [from string to `Error` with message](https://github.com/MichalLytek/class-transformer-validator/commit/e0ed33f9f8feb58d52bfdbc78f8150cdfd0ebe77#diff-f41e9d04a45c83f3b6f6e630f10117feR39)\n\n**0.1.0**\n\n- initial version with `transformAndValidate` function\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichallytek%2Fclass-transformer-validator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichallytek%2Fclass-transformer-validator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichallytek%2Fclass-transformer-validator/lists"}