{"id":13661139,"url":"https://github.com/typestack/class-sanitizer","last_synced_at":"2025-04-24T23:31:50.107Z","repository":{"id":57199512,"uuid":"56481887","full_name":"typestack/class-sanitizer","owner":"typestack","description":"Decorator based class property sanitation in Typescript.","archived":true,"fork":false,"pushed_at":"2020-07-31T20:23:49.000Z","size":248,"stargazers_count":100,"open_issues_count":0,"forks_count":19,"subscribers_count":4,"default_branch":"develop","last_synced_at":"2025-04-05T18:05:53.468Z","etag":null,"topics":["sanitizer","typescript"],"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/typestack.png","metadata":{"files":{"readme":"README.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}},"created_at":"2016-04-18T06:14:19.000Z","updated_at":"2024-07-30T15:20:56.000Z","dependencies_parsed_at":"2022-09-16T15:00:52.308Z","dependency_job_id":null,"html_url":"https://github.com/typestack/class-sanitizer","commit_stats":null,"previous_names":["pleerock/class-sanitizer"],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typestack%2Fclass-sanitizer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typestack%2Fclass-sanitizer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typestack%2Fclass-sanitizer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typestack%2Fclass-sanitizer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/typestack","download_url":"https://codeload.github.com/typestack/class-sanitizer/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250727692,"owners_count":21477351,"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":["sanitizer","typescript"],"created_at":"2024-08-02T05:01:30.250Z","updated_at":"2025-04-24T23:31:45.096Z","avatar_url":"https://github.com/typestack.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# class-sanitizer\n\n![Build Status](https://github.com/typestack/class-sanitizer/workflows/CI/badge.svg)\n[![codecov](https://codecov.io/gh/typestack/class-sanitizer/branch/master/graph/badge.svg)](https://codecov.io/gh/typestack/class-sanitizer)\n[![npm version](https://badge.fury.io/js/class-sanitizer.svg)](https://badge.fury.io/js/class-sanitizer)\n\nDecorator based class property sanitation in Typescript powered by [validator.js][validator.js].\n\n\u003e **DEPRECATION NOTICE:**  \n\u003e This library is considered to be deprecated and won't be updated anymore. Please use the [class-transformer][ct] and/or [class-validator][cv] libraries instead.\n\n## Installation\n\n```bash\nnpm install class-sanitizer --save\n```\n\n## Usage\n\nTo start using the library simply create some classes and add some sanitization decorators to the properties. When calling\n`sanitize(instance)` the library will automatically apply the rules defined in the decorators to the properties and update\nthe value of every marked property respectively.\n\n\u003e **NOTE:**  \n\u003e Every sanitization decorator is property decorator meaning it cannot be placed on parameters or class definitions.\n\n```typescript\nimport { sanitize, Trim } from 'class-sanitizer';\n\nclass TestClass {\n  @Trim()\n  label: string;\n\n  constructor(label: string) {\n    this.label = label;\n  }\n}\n\nconst instance = new TestClass(' text-with-spaces-on-both-end ');\n\nsanitize(instance);\n// -\u003e the label property is trimmed now\n// -\u003e { label: 'text-with-spaces-on-both-end' }\n```\n\n### Validating arrays\n\nEvery decorator expects a `SanitationOptions` object. When the `each` property is set to `true`\nthe array will be iterated and the decorator will be applied to every element of the array.\n\n```ts\nimport { sanitize, Trim } from 'class-sanitizer';\n\nclass TestClass {\n  @Trim(undefined, { each: true })\n  labels: string[];\n\n  constructor(labels: string[]) {\n    this.labels = labels;\n  }\n}\n\nconst instance = new TestClass([' labelA ', ' labelB', 'labelC ']);\n\nsanitize(instance);\n// -\u003e Every value is trimmed in instance.labels now.\n// -\u003e { labels: ['labelA', 'labelB', 'labelC']}\n```\n\n### Inheritance\n\nClass inheritance is supported, every decorator defined on the base-class will\nbe applied to the property with same name on the descendant class if the property exists.\n\n\u003e **Note**:  \n\u003e **Only one level of inheritance is supported!** So if you have `ClassA` inherit `ClassB` which inherits `ClassC` the\n\u003e decorators from `ClassC` won't be applied to `ClassA` when sanitizing.\n\n```ts\nimport { sanitize, Trim } from 'class-sanitizer';\n\nclass BaseClass {\n  @Trim()\n  baseText: string;\n}\n\nclass DescendantClass extends BaseClass {\n  @Trim()\n  descendantText: string;\n}\n\nconst instance = new DescendantClass();\ninstance.baseText = ' text ';\ninstance.descendantText = ' text ';\n\nsanitize(instance);\n// -\u003e Both value is trimmed now.\n// -\u003e { baseText: 'text', descendantText: 'text' }\n```\n\n### Sanitizing nested values with `@SanitizeNested()` decorator\n\nThe `@SanitizeNested` property can be used to instruct the library to lookup the sanitization rules\nfor the class instance found on the marked property and sanitize it.\n\n```ts\nimport { sanitize, Trim, SanitizeNested } from 'class-sanitizer';\n\nclass InnerTestClass {\n  @Trim()\n  text: string;\n\n  constructor(text: string) {\n    this.text = text;\n  }\n}\n\nclass TestClass {\n  @SanitizeNested({ each: true })\n  children: InnerTestClass[];\n\n  @SanitizeNested({ each: false })\n  child: InnerTestClass;\n}\n\nconst instance = new TestClass();\nconst innerA = new InnerTestClass(' innerA ');\nconst innerB = new InnerTestClass(' innerB ');\nconst innerC = new InnerTestClass(' innerC ');\ninstance.children = [innerA, innerB];\ninstance.child = innerC;\n\nsanitize(instance);\n// -\u003e Both values in the array on `children` property and value on `child` property is sanitized.\n// -\u003e { children: [ { text: 'innerA' }, { text: 'innerB' }], child: { 'innerC' }}\n```\n\n### Custom sanitation classes\n\nThe `@SanitizerConstraint(` decorator can be used to define custom sanitization logic. Creating a custom sanitization class requires the following steps:\n\n1. Create a class which implements the `CustomSanitizer` interface and decorate the class with the `@SanitizerConstraint()` decorator.\n\n   ```typescript\n   import { CustomSanitizer, SanitizerConstraint } from 'class-sanitizer';\n   import { Container } from 'typedi';\n\n   @SanitizerConstraint()\n   export class LetterReplacer implements CustomSanitizer {\n     /** If you use TypeDI, you can inject services to properties with `Container.get` function. */\n     someInjectedService = Container.get(SomeClass);\n\n     /**\n      * This function will be called during sanitization.\n      *  1, It must be a sync function\n      *  2, It must return the transformed value.\n      */\n\n     sanitize(text: string): string {\n       return text.replace(/o/g, 'w');\n     }\n   }\n   ```\n\n1. Then you can use your new sanitation constraint in your class:\n\n   ```typescript\n   import { Sanitize } from 'class-sanitizer';\n   import { LetterReplacer } from './LetterReplacer';\n\n   export class Post {\n     @Sanitize(LetterReplacer)\n     title: string;\n   }\n   ```\n\n1. Now you can use sanitizer as usual:\n\n   ```typescript\n   import { sanitize } from 'class-sanitizer';\n\n   sanitize(post);\n   ```\n\n### Manual sanitation\n\nThere are several method exist in the Sanitizer that allows to perform non-decorator based sanitation:\n\n```typescript\nimport Sanitizer from 'class-sanitizer';\n\nSanitizer.trim(` Let's trim this! `);\n```\n\n## Sanitization decorators\n\nThe following property decorators are available.\n\n| Decorator                              | Description                                                                                                                              |\n| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |\n| `@Blacklist(chars: string)`            | Removes all characters that appear in the blacklist.                                                                                     |\n| `@Whitelist(chars: string)`            | Removes all characters that don't appear in the whitelist.                                                                               |\n| `@Trim(chars?: string)`                | Trims characters (whitespace by default) from both sides of the input. You can specify chars that should be trimmed.                     |\n| `@Ltrim(chars?: string)`               | Trims characters from the left-side of the input.                                                                                        |\n| `@Rtrim(chars?: string)`               | Trims characters from the right-side of the input.                                                                                       |\n| `@Escape()`                            | Replaces \u003c, \u003e, \u0026, ', \" and / with HTML entities.                                                                                         |\n| `@NormalizeEmail(lowercase?: boolean)` | Normalizes an email address.                                                                                                             |\n| `@StripLow(keepNewLines?: boolean)`    | Removes characters with a numerical value \u003c 32 and 127, mostly control characters.                                                       |\n| `@ToBoolean(isStrict?: boolean)`       | Converts the input to a boolean. Everything except for '0', 'false' and '' returns true. In strict mode only '1' and 'true' return true. |\n| `@ToDate()`                            | Converts the input to a date, or null if the input is not a date.                                                                        |\n| `@ToFloat()`                           | Converts the input to a float, or NaN if the input is not an integer.                                                                    |\n| `@ToInt(radix?: number)`               | Converts the input to an integer, or NaN if the input is not an integer.                                                                 |\n| `@ToString()`                          | Converts the input to a string.                                                                                                          |\n\n[validator.js]: https://github.com/chriso/validator.js\n[typedi]: https://github.com/pleerock/typedi\n[ct]: https://github.com/typestack/class-transformer\n[cv]: https://github.com/typestack/class-validator\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftypestack%2Fclass-sanitizer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftypestack%2Fclass-sanitizer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftypestack%2Fclass-sanitizer/lists"}