Gathering detailed insights and metrics for validator.ts
Gathering detailed insights and metrics for validator.ts
Gathering detailed insights and metrics for validator.ts
Gathering detailed insights and metrics for validator.ts
npm install validator.ts
Module System
Unable to determine the module system for this package.
Min. Node Version
Typescript Support
Node Version
NPM Version
11,065 Stars
1,098 Commits
802 Forks
68 Watching
9 Branches
116 Contributors
Updated on 28 Nov 2024
TypeScript (99.81%)
JavaScript (0.19%)
Cumulative downloads
Total Downloads
Last day
22.7%
27
Compared to previous day
Last week
46.6%
192
Compared to previous week
Last month
-31.9%
810
Compared to previous month
Last year
-8.4%
11,984
Compared to previous year
Allows use of decorator and non-decorator based validation. Internally uses validator.js to perform validation. Class-validator works on both browser and node.js platforms.
1npm 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.
Create your class and put some validation decorators on the properties you want to validate:
1import { 2 validate, 3 validateOrReject, 4 Contains, 5 IsInt, 6 Length, 7 IsEmail, 8 IsFQDN, 9 IsDate, 10 Min, 11 Max, 12} from 'class-validator'; 13 14export class Post { 15 @Length(10, 20) 16 title: string; 17 18 @Contains('hello') 19 text: string; 20 21 @IsInt() 22 @Min(0) 23 @Max(10) 24 rating: number; 25 26 @IsEmail() 27 email: string; 28 29 @IsFQDN() 30 site: string; 31 32 @IsDate() 33 createDate: Date; 34} 35 36let post = new Post(); 37post.title = 'Hello'; // should not pass 38post.text = 'this is a great post about hell world'; // should not pass 39post.rating = 11; // should not pass 40post.email = 'google.com'; // should not pass 41post.site = 'googlecom'; // should not pass 42 43validate(post).then(errors => { 44 // errors is an array of validation errors 45 if (errors.length > 0) { 46 console.log('validation failed. errors: ', errors); 47 } else { 48 console.log('validation succeed'); 49 } 50}); 51 52validateOrReject(post).catch(errors => { 53 console.log('Promise rejected (validation failed). Errors: ', errors); 54}); 55// or 56async function validateOrRejectExample(input) { 57 try { 58 await validateOrReject(input); 59 } catch (errors) { 60 console.log('Caught promise rejection (validation failed). Errors: ', errors); 61 } 62}
The validate
function optionally expects a ValidatorOptions
object as a second parameter:
1export interface ValidatorOptions { 2 skipMissingProperties?: boolean; 3 whitelist?: boolean; 4 forbidNonWhitelisted?: boolean; 5 groups?: string[]; 6 dismissDefaultMessages?: boolean; 7 validationError?: { 8 target?: boolean; 9 value?: boolean; 10 }; 11 12 forbidUnknownValues?: boolean; 13 stopAtFirstError?: boolean; 14}
IMPORTANT The
forbidUnknownValues
value is set totrue
by default and it is highly advised to keep the default. Setting it tofalse
will result unknown objects passing the validation!
The validate
method returns an array of ValidationError
objects. Each ValidationError
is:
1{ 2 target: Object; // Object that was validated. 3 property: string; // Object's property that haven't pass validation. 4 value: any; // Value that haven't pass a validation. 5 constraints?: { // Constraints that failed validation with error messages. 6 [type: string]: string; 7 }; 8 children?: ValidationError[]; // Contains all nested validation errors of the property 9}
In our case, when we validated a Post object, we have such an array of ValidationError
objects:
1[{ 2 target: /* post object */, 3 property: "title", 4 value: "Hello", 5 constraints: { 6 length: "$property must be longer than or equal to 10 characters" 7 } 8}, { 9 target: /* post object */, 10 property: "text", 11 value: "this is a great post about hell world", 12 constraints: { 13 contains: "text must contain a hello string" 14 } 15}, 16// and other errors 17]
If you don't want a target
to be exposed in validation errors, there is a special option when you use validator:
1validator.validate(post, { validationError: { target: false } });
This is especially useful when you send errors back over http, and you most probably don't want to expose the whole target object.
You can specify validation message in the decorator options and that message will be returned in the ValidationError
returned by the validate
method (in the case that validation for this field fails).
1import { MinLength, MaxLength } from 'class-validator'; 2 3export class Post { 4 @MinLength(10, { 5 message: 'Title is too short', 6 }) 7 @MaxLength(50, { 8 message: 'Title is too long', 9 }) 10 title: string; 11}
There are few special tokens you can use in your messages:
$value
- the value that is being validated$property
- name of the object's property being validated$target
- name of the object's class being validated$constraint1
, $constraint2
, ... $constraintN
- constraints defined by specific validation typeExample of usage:
1import { MinLength, MaxLength } from 'class-validator'; 2 3export class Post { 4 @MinLength(10, { 5 // here, $constraint1 will be replaced with "10", and $value with actual supplied value 6 message: 'Title is too short. Minimal length is $constraint1 characters, but actual is $value', 7 }) 8 @MaxLength(50, { 9 // here, $constraint1 will be replaced with "50", and $value with actual supplied value 10 message: 'Title is too long. Maximal length is $constraint1 characters, but actual is $value', 11 }) 12 title: string; 13}
Also you can provide a function, that returns a message. This allows you to create more granular messages:
1import { MinLength, MaxLength, ValidationArguments } from 'class-validator'; 2 3export class Post { 4 @MinLength(10, { 5 message: (args: ValidationArguments) => { 6 if (args.value.length === 1) { 7 return 'Too short, minimum length is 1 character'; 8 } else { 9 return 'Too short, minimum length is ' + args.constraints[0] + ' characters'; 10 } 11 }, 12 }) 13 title: string; 14}
Message function accepts ValidationArguments
which contains the following information:
value
- the value that is being validatedconstraints
- array of constraints defined by specific validation typetargetName
- name of the object's class being validatedobject
- object that is being validatedproperty
- name of the object's property being validatedIf your field is an array and you want to perform validation of each item in the array you must specify a
special each: true
decorator option:
1import { MinLength, MaxLength } from 'class-validator'; 2 3export class Post { 4 @MaxLength(20, { 5 each: true, 6 }) 7 tags: string[]; 8}
This will validate each item in post.tags
array.
If your field is a set and you want to perform validation of each item in the set you must specify a
special each: true
decorator option:
1import { MinLength, MaxLength } from 'class-validator'; 2 3export class Post { 4 @MaxLength(20, { 5 each: true, 6 }) 7 tags: Set<string>; 8}
This will validate each item in post.tags
set.
If your field is a map and you want to perform validation of each item in the map you must specify a
special each: true
decorator option:
1import { MinLength, MaxLength } from 'class-validator'; 2 3export class Post { 4 @MaxLength(20, { 5 each: true, 6 }) 7 tags: Map<string, string>; 8}
This will validate each item in post.tags
map.
If your object contains nested objects and you want the validator to perform their validation too, then you need to
use the @ValidateNested()
decorator:
1import { ValidateNested } from 'class-validator'; 2 3export class Post { 4 @ValidateNested() 5 user: User; 6}
Please note that nested object must be an instance of a class, otherwise @ValidateNested
won't know what class is target of validation. Check also Validating plain objects.
It also works with multi-dimensional array, like :
1import { ValidateNested } from 'class-validator'; 2 3export class Plan2D { 4 @ValidateNested() 5 matrix: Point[][]; 6}
If your object contains property with Promise
-returned value that should be validated, then you need to use the @ValidatePromise()
decorator:
1import { ValidatePromise, Min } from 'class-validator'; 2 3export class Post { 4 @Min(0) 5 @ValidatePromise() 6 userId: Promise<number>; 7}
It also works great with @ValidateNested
decorator:
1import { ValidateNested, ValidatePromise } from 'class-validator'; 2 3export class Post { 4 @ValidateNested() 5 @ValidatePromise() 6 user: Promise<User>; 7}
When you define a subclass which extends from another one, the subclass will automatically inherit the parent's decorators. If a property is redefined in the descendant, class decorators will be applied on it from both its own class and the base class.
1import { validate } from 'class-validator'; 2 3class BaseContent { 4 @IsEmail() 5 email: string; 6 7 @IsString() 8 password: string; 9} 10 11class User extends BaseContent { 12 @MinLength(10) 13 @MaxLength(20) 14 name: string; 15 16 @Contains('hello') 17 welcome: string; 18 19 @MinLength(20) 20 password: string; 21} 22 23let user = new User(); 24 25user.email = 'invalid email'; // inherited property 26user.password = 'too short'; // password wil be validated not only against IsString, but against MinLength as well 27user.name = 'not valid'; 28user.welcome = 'helo'; 29 30validate(user).then(errors => { 31 // ... 32}); // it will return errors for email, password, name and welcome properties
The conditional validation decorator (@ValidateIf
) can be used to ignore the validators on a property when the provided condition function returns false. The condition function takes the object being validated and must return a boolean
.
1import { ValidateIf, IsNotEmpty } from 'class-validator'; 2 3export class Post { 4 otherProperty: string; 5 6 @ValidateIf(o => o.otherProperty === 'value') 7 @IsNotEmpty() 8 example: string; 9}
In the example above, the validation rules applied to example
won't be run unless the object's otherProperty
is "value"
.
Note that when the condition is false all validation decorators are ignored, including isDefined
.
Even if your object is an instance of a validation class it can contain additional properties that are not defined.
If you do not want to have such properties on your object, pass special flag to validate
method:
1import { validate } from 'class-validator'; 2// ... 3validate(post, { whitelist: true });
This will strip all properties that don't have any decorators. If no other decorator is suitable for your property, you can use @Allow decorator:
1import {validate, Allow, Min} from "class-validator"; 2 3export class Post { 4 5 @Allow() 6 title: string; 7 8 @Min(0) 9 views: number; 10 11 nonWhitelistedProperty: number; 12} 13 14let post = new Post(); 15post.title = 'Hello world!'; 16post.views = 420; 17 18post.nonWhitelistedProperty = 69; 19(post as any).anotherNonWhitelistedProperty = "something"; 20 21validate(post).then(errors => { 22 // post.nonWhitelistedProperty is not defined 23 // (post as any).anotherNonWhitelistedProperty is not defined 24 ... 25});
If you would rather to have an error thrown when any non-whitelisted properties are present, pass another flag to
validate
method:
1import { validate } from 'class-validator'; 2// ... 3validate(post, { whitelist: true, forbidNonWhitelisted: true });
It's possible to pass a custom object to decorators which will be accessible on the ValidationError
instance of the property if validation failed.
1import { validate } from 'class-validator';
2
3class MyClass {
4 @MinLength(32, {
5 message: 'EIC code must be at least 32 characters',
6 context: {
7 errorCode: 1003,
8 developerNote: 'The validated string must contain 32 or more characters.',
9 },
10 })
11 eicCode: string;
12}
13
14const model = new MyClass();
15
16validate(model).then(errors => {
17 //errors[0].contexts['minLength'].errorCode === 1003
18});
Sometimes you may want to skip validation of the properties that do not exist in the validating object. This is
usually desirable when you want to update some parts of the object, and want to validate only updated parts,
but skip everything else, e.g. skip missing properties.
In such situations you will need to pass a special flag to validate
method:
1import { validate } from 'class-validator'; 2// ... 3validate(post, { skipMissingProperties: true });
When skipping missing properties, sometimes you want not to skip all missing properties, some of them maybe required
for you, even if skipMissingProperties is set to true. For such cases you should use @IsDefined()
decorator.
@IsDefined()
is the only decorator that ignores skipMissingProperties
option.
In different situations you may want to use different validation schemas of the same object. In such cases you can use validation groups.
IMPORTANT Calling a validation with a group combination that would not result in a validation (eg: non existent group name) will result in a unknown value error. When validating with groups the provided group combination should match at least one decorator.
1import { validate, Min, Length } from 'class-validator'; 2 3export class User { 4 @Min(12, { 5 groups: ['registration'], 6 }) 7 age: number; 8 9 @Length(2, 20, { 10 groups: ['registration', 'admin'], 11 }) 12 name: string; 13} 14 15let user = new User(); 16user.age = 10; 17user.name = 'Alex'; 18 19validate(user, { 20 groups: ['registration'], 21}); // this will not pass validation 22 23validate(user, { 24 groups: ['admin'], 25}); // this will pass validation 26 27validate(user, { 28 groups: ['registration', 'admin'], 29}); // this will not pass validation 30 31validate(user, { 32 groups: undefined, // the default 33}); // this will not pass validation since all properties get validated regardless of their groups 34 35validate(user, { 36 groups: [], 37}); // this will not pass validation, (equivalent to 'groups: undefined', see above)
There is also a special flag always: true
in validation options that you can use. This flag says that this validation
must be applied always no matter which group is used.
If you have custom validation logic you can create a Constraint class:
First create a file, lets say CustomTextLength.ts
, and define a new class:
1import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator'; 2 3@ValidatorConstraint({ name: 'customText', async: false }) 4export class CustomTextLength implements ValidatorConstraintInterface { 5 validate(text: string, args: ValidationArguments) { 6 return text.length > 1 && text.length < 10; // for async validations you must return a Promise<boolean> here 7 } 8 9 defaultMessage(args: ValidationArguments) { 10 // here you can provide default error message if validation failed 11 return 'Text ($value) is too short or too long!'; 12 } 13}
We marked our class with @ValidatorConstraint
decorator.
You can also supply a validation constraint name - this name will be used as "error type" in ValidationError.
If you will not supply a constraint name - it will be auto-generated.
Our class must implement ValidatorConstraintInterface
interface and its validate
method,
which defines validation logic. If validation succeeds, method returns true, otherwise false.
Custom validator can be asynchronous, if you want to perform validation after some asynchronous
operations, simply return a promise with boolean inside in validate
method.
Also we defined optional method defaultMessage
which defines a default error message,
in the case that the decorator's implementation doesn't set an error message.
Then you can use your new validation constraint in your class:
1import { Validate } from 'class-validator'; 2import { CustomTextLength } from './CustomTextLength'; 3 4export class Post { 5 @Validate(CustomTextLength, { 6 message: 'Title is too short or long!', 7 }) 8 title: string; 9}
Here we set our newly created CustomTextLength
validation constraint for Post.title
.
And use validator as usual:
1import { validate } from 'class-validator'; 2 3validate(post).then(errors => { 4 // ... 5});
You can also pass constraints to your validator, like this:
1import { Validate } from 'class-validator'; 2import { CustomTextLength } from './CustomTextLength'; 3 4export class Post { 5 @Validate(CustomTextLength, [3, 20], { 6 message: 'Wrong post title', 7 }) 8 title: string; 9}
And use them from validationArguments
object:
1import { ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator'; 2 3@ValidatorConstraint() 4export class CustomTextLength implements ValidatorConstraintInterface { 5 validate(text: string, validationArguments: ValidationArguments) { 6 return text.length > validationArguments.constraints[0] && text.length < validationArguments.constraints[1]; 7 } 8}
You can also create a custom decorators. Its the most elegant way of using a custom validations.
Lets create a decorator called @IsLongerThan
:
Create a decorator itself:
1import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator'; 2 3export function IsLongerThan(property: string, validationOptions?: ValidationOptions) { 4 return function (object: Object, propertyName: string) { 5 registerDecorator({ 6 name: 'isLongerThan', 7 target: object.constructor, 8 propertyName: propertyName, 9 constraints: [property], 10 options: validationOptions, 11 validator: { 12 validate(value: any, args: ValidationArguments) { 13 const [relatedPropertyName] = args.constraints; 14 const relatedValue = (args.object as any)[relatedPropertyName]; 15 return typeof value === 'string' && typeof relatedValue === 'string' && value.length > relatedValue.length; // you can return a Promise<boolean> here as well, if you want to make async validation 16 }, 17 }, 18 }); 19 }; 20}
Put it to use:
1import { IsLongerThan } from './IsLongerThan'; 2 3export class Post { 4 title: string; 5 6 @IsLongerThan('title', { 7 /* you can also use additional validation options, like "groups" in your custom validation decorators. "each" is not supported */ 8 message: 'Text must be longer than the title', 9 }) 10 text: string; 11}
In your custom decorators you can also use ValidationConstraint
.
Lets create another custom validation decorator called IsUserAlreadyExist
:
Create a ValidationConstraint and decorator:
1import { 2 registerDecorator, 3 ValidationOptions, 4 ValidatorConstraint, 5 ValidatorConstraintInterface, 6 ValidationArguments, 7} from 'class-validator'; 8 9@ValidatorConstraint({ async: true }) 10export class IsUserAlreadyExistConstraint implements ValidatorConstraintInterface { 11 validate(userName: any, args: ValidationArguments) { 12 return UserRepository.findOneByName(userName).then(user => { 13 if (user) return false; 14 return true; 15 }); 16 } 17} 18 19export function IsUserAlreadyExist(validationOptions?: ValidationOptions) { 20 return function (object: Object, propertyName: string) { 21 registerDecorator({ 22 target: object.constructor, 23 propertyName: propertyName, 24 options: validationOptions, 25 constraints: [], 26 validator: IsUserAlreadyExistConstraint, 27 }); 28 }; 29}
note that we marked our constraint that it will by async by adding { async: true }
in validation options.
And put it to use:
1import { IsUserAlreadyExist } from './IsUserAlreadyExist'; 2 3export class User { 4 @IsUserAlreadyExist({ 5 message: 'User $value already exists. Choose another name.', 6 }) 7 name: string; 8}
Validator supports service container in the case if want to inject dependencies into your custom validator constraint classes. Here is example how to integrate it with typedi:
1import { Container } from 'typedi'; 2import { useContainer, Validator } from 'class-validator'; 3 4// do this somewhere in the global application level: 5useContainer(Container); 6let validator = Container.get(Validator); 7 8// now everywhere you can inject Validator class which will go from the container 9// also you can inject classes using constructor injection into your custom ValidatorConstraint-s
If you want to perform a simple non async validation you can use validateSync
method instead of regular validate
method. It has the same arguments as validate
method. But note, this method ignores all async validations
you have.
There are several method exist in the Validator that allows to perform non-decorator based validation:
1import { isEmpty, isBoolean } from 'class-validator'; 2 3isEmpty(value); 4isBoolean(value);
Decorator | Description |
---|---|
Common validation decorators | |
@IsDefined(value: any) | Checks if value is defined (!== undefined, !== null). This is the only decorator that ignores skipMissingProperties option. |
@IsOptional() | Checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property. |
@Equals(comparison: any) | Checks if value equals ("===") comparison. |
@NotEquals(comparison: any) | Checks if value not equal ("!==") comparison. |
@IsEmpty() | Checks if given value is empty (=== '', === null, === undefined). |
@IsNotEmpty() | Checks if given value is not empty (!== '', !== null, !== undefined). |
@IsIn(values: any[]) | Checks if value is in an array of allowed values. |
@IsNotIn(values: any[]) | Checks if value is not in an array of disallowed values. |
Type validation decorators | |
@IsBoolean() | Checks if a value is a boolean. |
@IsDate() | Checks if the value is a date. |
@IsString() | Checks if the value is a string. |
@IsNumber(options: IsNumberOptions) | Checks if the value is a number. |
@IsInt() | Checks if the value is an integer number. |
@IsArray() | Checks if the value is an array |
@IsEnum(entity: object) | Checks if the value is a valid enum |
Number validation decorators | |
@IsDivisibleBy(num: number) | Checks if the value is a number that's divisible by another. |
@IsPositive() | Checks if the value is a positive number greater than zero. |
@IsNegative() | Checks if the value is a negative number smaller than zero. |
@Min(min: number) | Checks if the given number is greater than or equal to given number. |
@Max(max: number) | Checks if the given number is less than or equal to given number. |
Date validation decorators | |
@MinDate(date: Date | (() => Date)) | Checks if the value is a date that's after the specified date. |
@MaxDate(date: Date | (() => Date)) | Checks if the value is a date that's before the specified date. |
String-type validation decorators | |
@IsBooleanString() | Checks if a string is a boolean (e.g. is "true" or "false" or "1", "0"). |
@IsDateString() | Alias for @IsISO8601() . |
@IsNumberString(options?: IsNumericOptions) | Checks if a string is a number. |
String validation decorators | |
@Contains(seed: string) | Checks if the string contains the seed. |
@NotContains(seed: string) | Checks if the string not contains the seed. |
@IsAlpha() | Checks if the string contains only letters (a-zA-Z). |
@IsAlphanumeric() | Checks if the string contains only letters and numbers. |
@IsDecimal(options?: IsDecimalOptions) | Checks if the string is a valid decimal value. Default IsDecimalOptions are force_decimal=False , decimal_digits: '1,' , locale: 'en-US' |
@IsAscii() | Checks if the string contains ASCII chars only. |
@IsBase32() | Checks if a string is base32 encoded. |
@IsBase58() | Checks if a string is base58 encoded. |
@IsBase64(options?: IsBase64Options) | Checks if a string is base64 encoded. |
@IsIBAN() | Checks if a string is a IBAN (International Bank Account Number). |
@IsBIC() | Checks if a string is a BIC (Bank Identification Code) or SWIFT code. |
@IsByteLength(min: number, max?: number) | Checks if the string's length (in bytes) falls in a range. |
@IsCreditCard() | Checks if the string is a credit card. |
@IsCurrency(options?: IsCurrencyOptions) | Checks if the string is a valid currency amount. |
@IsISO4217CurrencyCode() | Checks if the string is an ISO 4217 currency code. |
@IsEthereumAddress() | Checks if the string is an Ethereum address using basic regex. Does not validate address checksums. |
@IsBtcAddress() | Checks if the string is a valid BTC address. |
@IsDataURI() | Checks if the string is a data uri format. |
@IsEmail(options?: IsEmailOptions) | Checks if the string is an email. |
@IsFQDN(options?: IsFQDNOptions) | Checks if the string is a fully qualified domain name (e.g. domain.com). |
@IsFullWidth() | Checks if the string contains any full-width chars. |
@IsHalfWidth() | Checks if the string contains any half-width chars. |
@IsVariableWidth() | Checks if the string contains a mixture of full and half-width chars. |
@IsHexColor() | Checks if the string is a hexadecimal color. |
@IsHSL() | Checks if the string is an HSL color based on CSS Colors Level 4 specification. |
@IsRgbColor(options?: IsRgbOptions) | Checks if the string is a rgb or rgba color. |
@IsIdentityCard(locale?: string) | Checks if the string is a valid identity card code. |
@IsPassportNumber(countryCode?: string) | Checks if the string is a valid passport number relative to a specific country code. |
@IsPostalCode(locale?: string) | Checks if the string is a postal code. |
@IsHexadecimal() | Checks if the string is a hexadecimal number. |
@IsOctal() | Checks if the string is a octal number. |
@IsMACAddress(options?: IsMACAddressOptions) | Checks if the string is a MAC Address. |
@IsIP(version?: "4"|"6") | Checks if the string is an IP (version 4 or 6). |
@IsPort() | Checks if the string is a valid port number. |
@IsISBN(version?: "10"|"13") | Checks if the string is an ISBN (version 10 or 13). |
@IsEAN() | Checks if the string is an if the string is an EAN (European Article Number). |
@IsISIN() | Checks if the string is an ISIN (stock/security identifier). |
@IsISO8601(options?: IsISO8601Options) | Checks if the string is a valid ISO 8601 date format. Use the option strict = true for additional checks for a valid date. |
@IsJSON() | Checks if the string is valid JSON. |
@IsJWT() | Checks if the string is valid JWT. |
@IsObject() | Checks if the object is valid Object (null, functions, arrays will return false). |
@IsNotEmptyObject() | Checks if the object is not empty. |
@IsLowercase() | Checks if the string is lowercase. |
@IsLatLong() | Checks if the string is a valid latitude-longitude coordinate in the format lat, long. |
@IsLatitude() | Checks if the string or number is a valid latitude coordinate. |
@IsLongitude() | Checks if the string or number is a valid longitude coordinate. |
@IsMobilePhone(locale: string) | Checks if the string is a mobile phone number. |
@IsISO31661Alpha2() | Checks if the string is a valid ISO 3166-1 alpha-2 officially assigned country code. |
@IsISO31661Alpha3() | Checks if the string is a valid ISO 3166-1 alpha-3 officially assigned country code. |
@IsLocale() | Checks if the string is a locale. |
@IsPhoneNumber(region: string) | Checks if the string is a valid phone number using libphonenumber-js. |
@IsMongoId() | Checks if the string is a valid hex-encoded representation of a MongoDB ObjectId. |
@IsMultibyte() | Checks if the string contains one or more multibyte chars. |
@IsNumberString(options?: IsNumericOptions) | Checks if the string is numeric. |
@IsSurrogatePair() | Checks if the string contains any surrogate pairs chars. |
@IsTaxId() | Checks if the string is a valid tax ID. Default locale is en-US . |
@IsUrl(options?: IsURLOptions) | Checks if the string is a URL. |
@IsMagnetURI() | Checks if the string is a magnet uri format. |
@IsUUID(version?: UUIDVersion) | Checks if the string is a UUID (version 3, 4, 5 or all ). |
@IsFirebasePushId() | Checks if the string is a Firebase Push ID |
@IsUppercase() | Checks if the string is uppercase. |
@Length(min: number, max?: number) | Checks if the string's length falls in a range. |
@MinLength(min: number) | Checks if the string's length is not less than given number. |
@MaxLength(max: number) | Checks if the string's length is not more than given number. |
@Matches(pattern: RegExp, modifiers?: string) | Checks if string matches the pattern. Either matches('foo', /foo/i) or matches('foo', 'foo', 'i'). |
@IsMilitaryTime() | Checks if the string is a valid representation of military time in the format HH:MM. |
@IsTimeZone() | Checks if the string represents a valid IANA time-zone. |
@IsHash(algorithm: string) | Checks if the string is a hash The following types are supported:md4 , md5 , sha1 , sha256 , sha384 , sha512 , ripemd128 , ripemd160 , tiger128 , tiger160 , tiger192 , crc32 , crc32b . |
@IsMimeType() | Checks if the string matches to a valid MIME type format |
@IsSemVer() | Checks if the string is a Semantic Versioning Specification (SemVer). |
@IsISSN(options?: IsISSNOptions) | Checks if the string is a ISSN. |
@IsISRC() | Checks if the string is a ISRC. |
@IsRFC3339() | Checks if the string is a valid RFC 3339 date. |
@IsStrongPassword(options?: IsStrongPasswordOptions) | Checks if the string is a strong password. |
Array validation decorators | |
@ArrayContains(values: any[]) | Checks if array contains all values from the given array of values. |
@ArrayNotContains(values: any[]) | Checks if array does not contain any of the given values. |
@ArrayNotEmpty() | Checks if given array is not empty. |
@ArrayMinSize(min: number) | Checks if the array's length is greater than or equal to the specified number. |
@ArrayMaxSize(max: number) | Checks if the array's length is less or equal to the specified number. |
@ArrayUnique(identifier?: (o) => any) | Checks if all array's values are unique. Comparison for objects is reference-based. Optional function can be speciefied which return value will be used for the comparsion. |
Object validation decorators | |
@IsInstance(value: any) | Checks if the property is an instance of the passed value. |
Other decorators | |
@Allow() | Prevent stripping off the property when no other constraint is specified for it. |
Schema-based validation without decorators is no longer supported by class-validator
. This feature was broken in version 0.12 and it will not be fixed. If you are interested in schema-based validation, you can find several such frameworks in the zod readme's comparison section.
Due to nature of the decorators, the validated object has to be instantiated using new Class()
syntax. If you have your class defined using class-validator decorators and you want to validate plain JS object (literal object or returned by JSON.parse), you need to transform it to the class instance via using class-transformer).
Take a look on samples in ./sample for more examples of usages.
There are several extensions that simplify class-validator integration with other modules or add additional validations:
See information about breaking changes and release notes here.
For information about how to contribute to this project, see TypeStack's general contribution guide.
No vulnerabilities found.
Reason
all changesets reviewed
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
packaging workflow detected
Details
Reason
4 existing vulnerabilities detected
Details
Reason
1 commit(s) and 6 issue activity found in the last 90 days -- score normalized to 5
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More