Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/scopsy/typescript-param-validator
Typescript runtime parameters validation
https://github.com/scopsy/typescript-param-validator
decorators es2017 javascript typescript validation
Last synced: 3 months ago
JSON representation
Typescript runtime parameters validation
- Host: GitHub
- URL: https://github.com/scopsy/typescript-param-validator
- Owner: scopsy
- License: mit
- Created: 2018-01-17T00:07:09.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2018-01-17T14:02:13.000Z (almost 7 years ago)
- Last Synced: 2024-09-19T18:05:53.681Z (4 months ago)
- Topics: decorators, es2017, javascript, typescript, validation
- Language: TypeScript
- Homepage:
- Size: 246 KB
- Stars: 12
- Watchers: 2
- Forks: 2
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: code-of-conduct.md
Awesome Lists containing this project
README
# Typescript runtime param validation
A library for runtime param validations using typescript decorators
that works with `class-validator` library.
Useful when you need to validate parameter data coming from untyped source(i.e http body, and etc...) or when you need to perform complex validations on the input params.Using the param validation decorator you can declare your validation on the type annotation and leave the validation work to `class-validator`
## Install
```bash
npm install --save typescript-param-validator class-validators
```## Examples
```typescript
import { Validator, Validate } from 'typescript-param-validator';
import { IsDate, IsNotEmpty, MaxDate, IsEmail, Length } from 'class-validators';class DataDto {
@IsNotEmpty()
@IsEmail()
email: string;
@Length(10, 200)
@IsNotEmpty()
description: string;
@IsDate()
@IsNotEmpty()
@MaxDate(new Date())
birthDate: Date;
}class TestClass {
@Validate()
methodName(@Validator() data: DataDto) {
}@Validate()
serverControllerEndpoint(@Validator(DataDto, 'body') req: Request) {
}
}const instance = new TestClass();
// Will throw class-validator errors on runtime
instance.methodName({
birthDate: new Date(),
description: '123',
email: 'fakemail'
});instance.serverControllerEndpoint({
body: {
birthDate: new Date(),
description: '123',
email: 'fakemail'
}
});
```### Catching the Validation errors
In order to catch the validation errors you need to check if the errors is instanceof `ValidatorError`;
```typescript
import { ValidatorError } from 'typescript-param-validator';try {
// ... code
} catch (error) {
if (error instanceof ValidatorError) {
// here you have access to the validationErrors object that
// will contain array of `class-validator` error objects.
console.log(error.validationErrors);
}
}
```