11,853
stars
+0+0+17
845
forks
64
watchers
1,569
prs
1,067
issues
10
releases
–
discussions
README
class-validator
!Build Status
Allows use of decorator and non-decorator based validation.
Internally uses [validator.js][1] to perform validation.
Class-validator works on both browser and node.js platforms.
Table of Contents
- class-validator
- Table of Contents
- Installation
- Usage
- Passing options
- Validation errors
- Validation messages
- Validating arrays
- Validating sets
- Validating maps
- Validating nested objects
- Validating promises
- Inheriting Validation decorators
- Conditional validation
- Whitelisting
- Passing context to decorators
- Skipping missing properties
- Validation groups
- Custom validation classes
- Custom validation decorators
- Using service container
- Synchronous validation
- Manual validation
- Validation decorators
- Defining validation schema without decorators
- Validating plain objects
- Samples
- Extensions
- Release notes
- Contributing
Installation
sh
npm install class-validator --save
Note: Please use at least npm@6 when using class-validator. From npm@6 the dependency tree is flattened, which is required by class-validator to function properly.
Usage
Create your class and put some validation decorators on the properties you want to validate:
typescript
import {
validate,
validateOrReject,
Contains,
IsInt,
Length,
IsEmail,
IsFQDN,
IsDate,
Min,
Max,
} from 'class-validator';
export class Post {
@Length(10, 20)
title: string;
@Contains('hello')
text: string;
@IsInt()
@Min(0)
@Max(10)
rating: number;
@IsEmail()
email: string;
@IsFQDN()
site: string;
@IsDate()
createDate: Date;
}
let post = new Post();
post.title = 'Hello'; // should not pass
post.text = 'this is a great post about hell world'; // should not pass
post.rating = 11; // should not pass
post.email = 'google.com'; // should not pass
post.site = 'googlecom'; // should not pass
validate(post).then(errors = {
// errors is an array of validation errors
if (errors.length 0) {
console.log('validation failed. errors: ', errors);
} else {
console.log('validation succeed');
}
});
validateOrReject(post).catch(errors = {
console.log('Promise rejected (validation failed). Errors: ', errors);
});
// or
async function validateOrRejectExample(input) {
try {
await validateOrReject(input);
} catch (errors) {
console.log('Caught promise rejection (validation failed). Errors: ', errors);
}
}
Passing options
The validate function optionally expects a ValidatorOptions object as a second parameter:
ts
export interface ValidatorOptions {
skipMissingProperties?: boolean;
whitelist?: boolean;
forbidNonWhitelisted?: boolean;
groups?: string[];
dismissDefaultMessages?: boolean;
validationError?: {
target?: boolean;
value?: boolean;
};
forbidUnknownValues?: boolean;
stopAtFirstError?: boolean;
}
IMPORTANT
The forbidUnknownValues value is set to true by default and it is