Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

class-validator

Package Overview
Dependencies
Maintainers
2
Versions
58
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

class-validator - npm Package Compare versions

Comparing version 0.7.3 to 0.8.0

2

container.js

@@ -7,3 +7,3 @@ "use strict";

*/
var defaultContainer = new ((function () {
var defaultContainer = new (/** @class */ (function () {
function class_1() {

@@ -10,0 +10,0 @@ this.instances = [];

@@ -1,2 +0,2 @@

import { IsEmailOptions, IsFQDNOptions, IsURLOptions, IsCurrencyOptions } from "../validation/ValidationTypeOptions";
import { IsEmailOptions, IsFQDNOptions, IsURLOptions, IsCurrencyOptions, IsNumberOptions } from "../validation/ValidationTypeOptions";
import { ValidationOptions } from "./ValidationOptions";

@@ -21,2 +21,6 @@ /**

/**
* If object has both allowed and not allowed properties a validation error will be thrown.
*/
export declare function Allow(validationOptions?: ValidationOptions): (object: Object, propertyName: string) => void;
/**
* Objects / object arrays marked with this decorator will also be validated.

@@ -68,3 +72,3 @@ */

*/
export declare function IsNumber(validationOptions?: ValidationOptions): (object: Object, propertyName: string) => void;
export declare function IsNumber(options?: IsNumberOptions, validationOptions?: ValidationOptions): (object: Object, propertyName: string) => void;
/**

@@ -285,1 +289,5 @@ * Checks if the value is an integer number.

export declare function ArrayUnique(validationOptions?: ValidationOptions): (object: Object, propertyName: string) => void;
/**
* Checks if all array's values are unique. Comparison for objects is reference-based.
*/
export declare function IsInstance(targetType: new (...args: any[]) => any, validationOptions?: ValidationOptions): (object: Object, propertyName: string) => void;

@@ -58,2 +58,17 @@ "use strict";

/**
* If object has both allowed and not allowed properties a validation error will be thrown.
*/
function Allow(validationOptions) {
return function (object, propertyName) {
var args = {
type: ValidationTypes_1.ValidationTypes.WHITELIST,
target: object.constructor,
propertyName: propertyName,
validationOptions: validationOptions
};
container_1.getFromContainer(MetadataStorage_1.MetadataStorage).addValidationMetadata(new ValidationMetadata_1.ValidationMetadata(args));
};
}
exports.Allow = Allow;
/**
* Objects / object arrays marked with this decorator will also be validated.

@@ -240,3 +255,4 @@ */

*/
function IsNumber(validationOptions) {
function IsNumber(options, validationOptions) {
if (options === void 0) { options = {}; }
return function (object, propertyName) {

@@ -247,2 +263,3 @@ var args = {

propertyName: propertyName,
constraints: [options],
validationOptions: validationOptions

@@ -1106,3 +1123,19 @@ };

exports.ArrayUnique = ArrayUnique;
/**
* Checks if all array's values are unique. Comparison for objects is reference-based.
*/
function IsInstance(targetType, validationOptions) {
return function (object, propertyName) {
var args = {
type: ValidationTypes_1.ValidationTypes.IS_INSTANCE,
target: object.constructor,
propertyName: propertyName,
constraints: [targetType],
validationOptions: validationOptions
};
container_1.getFromContainer(MetadataStorage_1.MetadataStorage).addValidationMetadata(new ValidationMetadata_1.ValidationMetadata(args));
};
}
exports.IsInstance = IsInstance;
//# sourceMappingURL=decorators.js.map

@@ -7,3 +7,3 @@ "use strict";

*/
var ConstraintMetadata = (function () {
var ConstraintMetadata = /** @class */ (function () {
// -------------------------------------------------------------------------

@@ -10,0 +10,0 @@ // Constructor

@@ -7,3 +7,3 @@ "use strict";

*/
var MetadataStorage = (function () {
var MetadataStorage = /** @class */ (function () {
function MetadataStorage() {

@@ -10,0 +10,0 @@ // -------------------------------------------------------------------------

@@ -6,3 +6,3 @@ "use strict";

*/
var ValidationMetadata = (function () {
var ValidationMetadata = /** @class */ (function () {
// -------------------------------------------------------------------------

@@ -9,0 +9,0 @@ // Constructor

{
"name": "class-validator",
"private": false,
"version": "0.7.3",
"version": "0.8.0",
"description": "Class-based validation with Typescript / ES6 / ES5 using decorators or validation schemas. Supports both node.js and browser",

@@ -26,3 +26,3 @@ "license": "MIT",

"dependencies": {
"validator": "^7.0.0"
"validator": "9.2.0"
},

@@ -29,0 +29,0 @@ "devDependencies": {

# class-validator
[![Build Status](https://travis-ci.org/pleerock/class-validator.svg?branch=master)](https://travis-ci.org/pleerock/class-validator)
[![Build Status](https://travis-ci.org/typestack/class-validator.svg?branch=master)](https://travis-ci.org/typestack/class-validator)
[![npm version](https://badge.fury.io/js/class-validator.svg)](https://badge.fury.io/js/class-validator)
[![Join the chat at https://gitter.im/pleerock/class-validator](https://badges.gitter.im/pleerock/class-validator.svg)](https://gitter.im/pleerock/class-validator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Join the chat at https://gitter.im/typestack/class-validator](https://badges.gitter.im/typestack/class-validator.svg)](https://gitter.im/typestack/class-validator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

@@ -118,3 +118,3 @@ Allows use of decorator and non-decorator based validation.

constraints: {
length: "$property must be longer than 10 characters"
length: "$property must be longer than or equal to 10 characters"
}

@@ -300,2 +300,54 @@ }, {

## Whitelisting
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:
```javascript
import {validate} from "class-validator";
// ...
validate(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:
```javascript
import {validate, Allow, Min} from "class-validator";
export class Post {
@Allow()
title: string;
@Min(0)
views: number;
nonWhitelistedProperty: number;
}
let post = new Post();
post.title = 'Hello world!';
post.views = 420;
post.nonWhitelistedProperty = 69;
(post as any).anotherNonWhitelistedProperty = "something";
validate(post).then(errors => {
// post.nonWhitelistedProperty is not defined
// (post as any).anotherNonWhitelistedProperty is not defined
...
});
````
If you would rather to have an error thrown when any non-whitelisted properties are present, pass another flag to
`validate` method:
```javascript
import {validate} from "class-validator";
// ...
validate(post, { whitelist: true, forbidNonWhitelisted: true });
```
## Skipping missing properties

@@ -357,3 +409,3 @@

groups: []
}); // this will pass validation
}); // this will not pass validation
```

@@ -606,3 +658,3 @@

validator.isArray(value); // Checks if a given value is an array.
validator.isNumber(value); // Checks if a given value is a real number.
validator.isNumber(value, options); // Checks if a given value is a real number.
validator.isInt(value); // Checks if value is an integer.

@@ -669,2 +721,5 @@ validator.isEnum(value, entity); // Checks if value is valid for a certain enum entity.

validator.arrayUnique(array); // Checks if all array's values are unique. Comparison for objects is reference-based.
// object validation methods
validator.isInstance(value, target); // Checks value is an instance of the target.
```

@@ -687,8 +742,8 @@

| `@IsBoolean()` | Checks if a value is a boolean. |
| `@IsDate()` | Checks if the string is a date. |
| `@IsDate()` | Checks if the value is a date. |
| `@IsString()` | Checks if the string is a string. |
| `@IsNumber()` | Checks if the string is a number. |
| `@IsNumber(options: IsNumberOptions)` | Checks if the value is a number. |
| `@IsInt()` | Checks if the value is an integer number. |
| `@IsArray()` | Checks if the string is an array |
| `@IsEnum(entity: object)` | Checks if the value is an valid enum |
| `@IsArray()` | Checks if the value is an array |
| `@IsEnum(entity: object)` | Checks if the value is an valid enum |
| **Number validation decorators** |

@@ -705,3 +760,3 @@ | `@IsDivisibleBy(num: number)` | Checks if the value is a number that's divisible by another. |

| `@IsBooleanString()` | Checks if a string is a boolean (e.g. is "true" or "false"). |
| `@IsDateString()` | Checks if a string is a date (e.g. "2017-06-07T14:34:08.700Z" or "2017-06-07T14:34:08.700"). |
| `@IsDateString()` | Checks if a string is a complete representation of a date (e.g. "2017-06-07T14:34:08.700Z", "2017-06-07T14:34:08.700 or "2017-06-07T14:34:08+04:00"). |
| `@IsNumberString()` | Checks if a string is a number. |

@@ -725,4 +780,4 @@ | **String validation decorators** |

| `@IsHexadecimal()` | Checks if the string is a hexadecimal number. |
| `@IsIP(version?: "4"|"6")` | Checks if the string is an IP (version 4 or 6). |
| `@IsISBN(version?: "10"|"13")` | Checks if the string is an ISBN (version 10 or 13). |
| `@IsIP(version?: "4"\|"6")` | Checks if the string is an IP (version 4 or 6). |
| `@IsISBN(version?: "10"\|"13")` | Checks if the string is an ISBN (version 10 or 13). |
| `@IsISIN()` | Checks if the string is an ISIN (stock/security identifier). |

@@ -738,3 +793,3 @@ | `@IsISO8601()` | Checks if the string is a valid ISO 8601 date. |

| `@IsUrl(options?: IsURLOptions)` | Checks if the string is an url. |
| `@IsUUID(version?: "3"|"4"|"5")` | Checks if the string is a UUID (version 3, 4 or 5). |
| `@IsUUID(version?: "3"\|"4"\|"5")` | Checks if the string is a UUID (version 3, 4 or 5). |
| `@IsUppercase()` | Checks if the string is uppercase. |

@@ -745,5 +800,5 @@ | `@Length(min: number, max?: number)` | Checks if the string's length falls in a range. |

| `@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.
| `@IsMilitaryTime()` | Checks if the string is a valid representation of military time in the format HH:MM. |
| **Array validation decorators** |
| `@ArrayContains(values: any[])` | Checks if array contains all values from the given array of values. |
| `@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. |

@@ -753,3 +808,7 @@ | `@ArrayNotEmpty()` | Checks if given array is not empty. |

| `@ArrayMaxSize(max: number)` | Checks if array's length is as maximal this number. |
| `@ArrayUnique()` | Checks if all array's values are unique. Comparison for objects is reference-based. |
| `@ArrayUnique()` | Checks if all array's values are unique. Comparison for objects is reference-based. |
| **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. |

@@ -756,0 +815,0 @@ ## Defining validation schema without decorators

@@ -18,3 +18,3 @@ "use strict";

var validator_1 = options.validator;
constraintCls = (function () {
constraintCls = /** @class */ (function () {
function CustomConstraint() {

@@ -21,0 +21,0 @@ }

@@ -8,3 +8,3 @@ "use strict";

*/
var ValidationSchemaToMetadataTransformer = (function () {
var ValidationSchemaToMetadataTransformer = /** @class */ (function () {
function ValidationSchemaToMetadataTransformer() {

@@ -11,0 +11,0 @@ }

@@ -6,3 +6,3 @@ "use strict";

*/
var ValidationError = (function () {
var ValidationError = /** @class */ (function () {
function ValidationError() {

@@ -9,0 +9,0 @@ }

import { Validator } from "./Validator";
import { ValidationError } from "./ValidationError";
import { ValidationMetadata } from "../metadata/ValidationMetadata";
import { ValidatorOptions } from "./ValidatorOptions";

@@ -15,2 +16,5 @@ /**

execute(object: Object, targetSchema: string, validationErrors: ValidationError[]): void;
whitelist(object: any, groupedMetadatas: {
[propertyName: string]: ValidationMetadata[];
}, validationErrors: ValidationError[]): void;
stripEmptyErrors(errors: ValidationError[]): ValidationError[];

@@ -17,0 +21,0 @@ private generateValidationError(object, value, propertyName);

@@ -11,3 +11,3 @@ "use strict";

*/
var ValidationExecutor = (function () {
var ValidationExecutor = /** @class */ (function () {
// -------------------------------------------------------------------------

@@ -37,6 +37,9 @@ // Constructor

var groupedMetadatas = this.metadataStorage.groupByPropertyName(targetMetadatas);
if (this.validatorOptions && this.validatorOptions.whitelist)
this.whitelist(object, groupedMetadatas, validationErrors);
// General validation
Object.keys(groupedMetadatas).forEach(function (propertyName) {
var value = object[propertyName];
var definedMetadatas = groupedMetadatas[propertyName].filter(function (metadata) { return metadata.type === ValidationTypes_1.ValidationTypes.IS_DEFINED; });
var metadatas = groupedMetadatas[propertyName].filter(function (metadata) { return metadata.type !== ValidationTypes_1.ValidationTypes.IS_DEFINED; });
var metadatas = groupedMetadatas[propertyName].filter(function (metadata) { return metadata.type !== ValidationTypes_1.ValidationTypes.IS_DEFINED && metadata.type !== ValidationTypes_1.ValidationTypes.WHITELIST; });
var customValidationMetadatas = metadatas.filter(function (metadata) { return metadata.type === ValidationTypes_1.ValidationTypes.CUSTOM_VALIDATION; });

@@ -61,2 +64,26 @@ var nestedValidationMetadatas = metadatas.filter(function (metadata) { return metadata.type === ValidationTypes_1.ValidationTypes.NESTED_VALIDATION; });

};
ValidationExecutor.prototype.whitelist = function (object, groupedMetadatas, validationErrors) {
var notAllowedProperties = [];
Object.keys(object).forEach(function (propertyName) {
// does this property have no metadata?
if (!groupedMetadatas[propertyName] || groupedMetadatas[propertyName].length === 0)
notAllowedProperties.push(propertyName);
});
if (notAllowedProperties.length > 0) {
if (this.validatorOptions && this.validatorOptions.forbidNonWhitelisted) {
// throw errors
notAllowedProperties.forEach(function (property) {
validationErrors.push({
target: object, property: property, value: object[property], children: undefined,
constraints: (_a = {}, _a[ValidationTypes_1.ValidationTypes.WHITELIST] = "property " + property + " should not exist", _a)
});
var _a;
});
}
else {
// strip non allowed properties
notAllowedProperties.forEach(function (property) { return delete object[property]; });
}
}
};
ValidationExecutor.prototype.stripEmptyErrors = function (errors) {

@@ -176,4 +203,13 @@ var _this = this;

else {
throw new Error("Only objects and arrays are supported to nested validation");
var error = new ValidationError_1.ValidationError();
error.value = value;
error.property = metadata.propertyName;
error.target = metadata.target;
var _a = _this.createValidationError(metadata.target, value, metadata), type = _a[0], message = _a[1];
error.constraints = (_b = {},
_b[type] = message,
_b);
errors.push(error);
}
var _b;
});

@@ -180,0 +216,0 @@ };

/**
* Options to be passed to IsURL decorator.
*/
export interface IsNumberOptions {
allowNaN?: boolean;
allowInfinity?: boolean;
}
/**
* Options to be passed to IsCurrency decorator.

@@ -3,0 +10,0 @@ */

@@ -9,2 +9,3 @@ import { ValidationArguments } from "./ValidationArguments";

static CONDITIONAL_VALIDATION: string;
static WHITELIST: string;
static IS_DEFINED: string;

@@ -74,2 +75,3 @@ static EQUALS: string;

static ARRAY_UNIQUE: string;
static IS_INSTANCE: string;
/**

@@ -76,0 +78,0 @@ * Checks if validation type is valid.

@@ -6,3 +6,3 @@ "use strict";

*/
var ValidationTypes = (function () {
var ValidationTypes = /** @class */ (function () {
function ValidationTypes() {

@@ -23,4 +23,8 @@ }

ValidationTypes.getMessage = function (type, isEach) {
var _this = this;
var eachPrefix = isEach ? "each value in " : "";
switch (type) {
/* system chceck */
case this.NESTED_VALIDATION:
return eachPrefix + "nested property $property must be either object or array";
/* common checkers */

@@ -143,8 +147,8 @@ case this.IS_DEFINED:

if (isMinLength && (!args.value || args.value.length < args.constraints[0])) {
return eachPrefix + "$property must be longer than $constraint1 characters";
return eachPrefix + "$property must be longer than or equal to $constraint1 characters";
}
else if (isMaxLength && (args.value.length > args.constraints[1])) {
return eachPrefix + "$property must be shorter than $constraint2 characters";
return eachPrefix + "$property must be shorter than or equal to $constraint2 characters";
}
return eachPrefix + "$property must be longer than $constraint1 and shorter than $constraint2 characters";
return eachPrefix + "$property must be longer than or equal to $constraint1 and shorter than or equal to $constraint2 characters";
};

@@ -170,84 +174,96 @@ case this.MIN_LENGTH:

return eachPrefix + "All $property's elements must be unique";
case this.IS_INSTANCE:
return function (args) {
if (args.constraints[0]) {
return eachPrefix + ("$property must be an instance of " + args.constraints[0].name);
}
else {
return eachPrefix + (_this.IS_INSTANCE + " decorator expects and object as value, but got falsy value.");
}
};
}
return "";
};
/* system */
ValidationTypes.CUSTOM_VALIDATION = "customValidation";
ValidationTypes.NESTED_VALIDATION = "nestedValidation";
ValidationTypes.CONDITIONAL_VALIDATION = "conditionalValidation";
ValidationTypes.WHITELIST = "whitelistValidation";
/* common checkers */
ValidationTypes.IS_DEFINED = "isDefined";
ValidationTypes.EQUALS = "equals";
ValidationTypes.NOT_EQUALS = "notEquals";
ValidationTypes.IS_EMPTY = "isEmpty";
ValidationTypes.IS_NOT_EMPTY = "isNotEmpty";
ValidationTypes.IS_IN = "isIn";
ValidationTypes.IS_NOT_IN = "isNotIn";
/* type checkers */
ValidationTypes.IS_BOOLEAN = "isBoolean";
ValidationTypes.IS_DATE = "isDate";
ValidationTypes.IS_NUMBER = "isNumber";
ValidationTypes.IS_STRING = "isString";
ValidationTypes.IS_DATE_STRING = "isDateString";
ValidationTypes.IS_ARRAY = "isArray";
ValidationTypes.IS_INT = "isInt";
ValidationTypes.IS_ENUM = "isEnum";
/* number checkers */
ValidationTypes.IS_DIVISIBLE_BY = "isDivisibleBy";
ValidationTypes.IS_POSITIVE = "isPositive";
ValidationTypes.IS_NEGATIVE = "isNegative";
ValidationTypes.MIN = "min";
ValidationTypes.MAX = "max";
/* date checkers */
ValidationTypes.MIN_DATE = "minDate";
ValidationTypes.MAX_DATE = "maxDate";
/* string-as-type checkers */
ValidationTypes.IS_BOOLEAN_STRING = "isBooleanString";
ValidationTypes.IS_NUMBER_STRING = "isNumberString";
/* string checkers */
ValidationTypes.CONTAINS = "contains";
ValidationTypes.NOT_CONTAINS = "notContains";
ValidationTypes.IS_ALPHA = "isAlpha";
ValidationTypes.IS_ALPHANUMERIC = "isAlphanumeric";
ValidationTypes.IS_ASCII = "isAscii";
ValidationTypes.IS_BASE64 = "isBase64";
ValidationTypes.IS_BYTE_LENGTH = "isByteLength";
ValidationTypes.IS_CREDIT_CARD = "isCreditCard";
ValidationTypes.IS_CURRENCY = "isCurrency";
ValidationTypes.IS_EMAIL = "isEmail";
ValidationTypes.IS_FQDN = "isFqdn";
ValidationTypes.IS_FULL_WIDTH = "isFullWidth";
ValidationTypes.IS_HALF_WIDTH = "isHalfWidth";
ValidationTypes.IS_VARIABLE_WIDTH = "isVariableWidth";
ValidationTypes.IS_HEX_COLOR = "isHexColor";
ValidationTypes.IS_HEXADECIMAL = "isHexadecimal";
ValidationTypes.IS_IP = "isIp";
ValidationTypes.IS_ISBN = "isIsbn";
ValidationTypes.IS_ISIN = "isIsin";
ValidationTypes.IS_ISO8601 = "isIso8601";
ValidationTypes.IS_JSON = "isJson";
ValidationTypes.IS_LOWERCASE = "isLowercase";
ValidationTypes.IS_MOBILE_PHONE = "isMobilePhone";
ValidationTypes.IS_MONGO_ID = "isMongoId";
ValidationTypes.IS_MULTIBYTE = "isMultibyte";
ValidationTypes.IS_SURROGATE_PAIR = "isSurrogatePair";
ValidationTypes.IS_URL = "isUrl";
ValidationTypes.IS_UUID = "isUuid";
ValidationTypes.LENGTH = "length";
ValidationTypes.IS_UPPERCASE = "isUppercase";
ValidationTypes.MIN_LENGTH = "minLength";
ValidationTypes.MAX_LENGTH = "maxLength";
ValidationTypes.MATCHES = "matches";
ValidationTypes.IS_MILITARY_TIME = "isMilitaryTime";
/* array checkers */
ValidationTypes.ARRAY_CONTAINS = "arrayContains";
ValidationTypes.ARRAY_NOT_CONTAINS = "arrayNotContains";
ValidationTypes.ARRAY_NOT_EMPTY = "arrayNotEmpty";
ValidationTypes.ARRAY_MIN_SIZE = "arrayMinSize";
ValidationTypes.ARRAY_MAX_SIZE = "arrayMaxSize";
ValidationTypes.ARRAY_UNIQUE = "arrayUnique";
/* object chekers */
ValidationTypes.IS_INSTANCE = "isInstance";
return ValidationTypes;
}());
/* system */
ValidationTypes.CUSTOM_VALIDATION = "customValidation";
ValidationTypes.NESTED_VALIDATION = "nestedValidation";
ValidationTypes.CONDITIONAL_VALIDATION = "conditionalValidation";
/* common checkers */
ValidationTypes.IS_DEFINED = "isDefined";
ValidationTypes.EQUALS = "equals";
ValidationTypes.NOT_EQUALS = "notEquals";
ValidationTypes.IS_EMPTY = "isEmpty";
ValidationTypes.IS_NOT_EMPTY = "isNotEmpty";
ValidationTypes.IS_IN = "isIn";
ValidationTypes.IS_NOT_IN = "isNotIn";
/* type checkers */
ValidationTypes.IS_BOOLEAN = "isBoolean";
ValidationTypes.IS_DATE = "isDate";
ValidationTypes.IS_NUMBER = "isNumber";
ValidationTypes.IS_STRING = "isString";
ValidationTypes.IS_DATE_STRING = "isDateString";
ValidationTypes.IS_ARRAY = "isArray";
ValidationTypes.IS_INT = "isInt";
ValidationTypes.IS_ENUM = "isEnum";
/* number checkers */
ValidationTypes.IS_DIVISIBLE_BY = "isDivisibleBy";
ValidationTypes.IS_POSITIVE = "isPositive";
ValidationTypes.IS_NEGATIVE = "isNegative";
ValidationTypes.MIN = "min";
ValidationTypes.MAX = "max";
/* date checkers */
ValidationTypes.MIN_DATE = "minDate";
ValidationTypes.MAX_DATE = "maxDate";
/* string-as-type checkers */
ValidationTypes.IS_BOOLEAN_STRING = "isBooleanString";
ValidationTypes.IS_NUMBER_STRING = "isNumberString";
/* string checkers */
ValidationTypes.CONTAINS = "contains";
ValidationTypes.NOT_CONTAINS = "notContains";
ValidationTypes.IS_ALPHA = "isAlpha";
ValidationTypes.IS_ALPHANUMERIC = "isAlphanumeric";
ValidationTypes.IS_ASCII = "isAscii";
ValidationTypes.IS_BASE64 = "isBase64";
ValidationTypes.IS_BYTE_LENGTH = "isByteLength";
ValidationTypes.IS_CREDIT_CARD = "isCreditCard";
ValidationTypes.IS_CURRENCY = "isCurrency";
ValidationTypes.IS_EMAIL = "isEmail";
ValidationTypes.IS_FQDN = "isFqdn";
ValidationTypes.IS_FULL_WIDTH = "isFullWidth";
ValidationTypes.IS_HALF_WIDTH = "isHalfWidth";
ValidationTypes.IS_VARIABLE_WIDTH = "isVariableWidth";
ValidationTypes.IS_HEX_COLOR = "isHexColor";
ValidationTypes.IS_HEXADECIMAL = "isHexadecimal";
ValidationTypes.IS_IP = "isIp";
ValidationTypes.IS_ISBN = "isIsbn";
ValidationTypes.IS_ISIN = "isIsin";
ValidationTypes.IS_ISO8601 = "isIso8601";
ValidationTypes.IS_JSON = "isJson";
ValidationTypes.IS_LOWERCASE = "isLowercase";
ValidationTypes.IS_MOBILE_PHONE = "isMobilePhone";
ValidationTypes.IS_MONGO_ID = "isMongoId";
ValidationTypes.IS_MULTIBYTE = "isMultibyte";
ValidationTypes.IS_SURROGATE_PAIR = "isSurrogatePair";
ValidationTypes.IS_URL = "isUrl";
ValidationTypes.IS_UUID = "isUuid";
ValidationTypes.LENGTH = "length";
ValidationTypes.IS_UPPERCASE = "isUppercase";
ValidationTypes.MIN_LENGTH = "minLength";
ValidationTypes.MAX_LENGTH = "maxLength";
ValidationTypes.MATCHES = "matches";
ValidationTypes.IS_MILITARY_TIME = "isMilitaryTime";
/* array checkers */
ValidationTypes.ARRAY_CONTAINS = "arrayContains";
ValidationTypes.ARRAY_NOT_CONTAINS = "arrayNotContains";
ValidationTypes.ARRAY_NOT_EMPTY = "arrayNotEmpty";
ValidationTypes.ARRAY_MIN_SIZE = "arrayMinSize";
ValidationTypes.ARRAY_MAX_SIZE = "arrayMaxSize";
ValidationTypes.ARRAY_UNIQUE = "arrayUnique";
exports.ValidationTypes = ValidationTypes;
//# sourceMappingURL=ValidationTypes.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ValidationUtils = (function () {
var ValidationUtils = /** @class */ (function () {
function ValidationUtils() {

@@ -5,0 +5,0 @@ }

import { ValidationMetadata } from "../metadata/ValidationMetadata";
import { ValidationError } from "./ValidationError";
import { IsEmailOptions, IsFQDNOptions, IsURLOptions, IsCurrencyOptions } from "./ValidationTypeOptions";
import { IsEmailOptions, IsFQDNOptions, IsURLOptions, IsCurrencyOptions, IsNumberOptions } from "./ValidationTypeOptions";
import { ValidatorOptions } from "./ValidatorOptions";

@@ -97,5 +97,5 @@ /**

/**
* Checks if a given value is a real number.
* Checks if a given value is a number.
*/
isNumber(value: any): boolean;
isNumber(value: any, options?: IsNumberOptions): boolean;
/**

@@ -344,2 +344,6 @@ * Checks if value is an integer.

arrayUnique(array: any[]): boolean;
/**
* Checks if the value is an instance of the specified object.
*/
isInstance(object: any, targetTypeConstructor: new (...args: any[]) => any): boolean;
}

@@ -11,4 +11,4 @@ "use strict";

var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
return { next: verb(0), "throw": verb(1), "return": verb(2) };
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }

@@ -44,3 +44,3 @@ function step(op) {

*/
var Validator = (function () {
var Validator = /** @class */ (function () {
function Validator() {

@@ -136,3 +136,3 @@ // -------------------------------------------------------------------------

case ValidationTypes_1.ValidationTypes.IS_NUMBER:
return this.isNumber(value);
return this.isNumber(value, metadata.constraints[0]);
case ValidationTypes_1.ValidationTypes.IS_INT:

@@ -245,2 +245,4 @@ return this.isInt(value);

return this.arrayUnique(value);
case ValidationTypes_1.ValidationTypes.IS_INSTANCE:
return this.isInstance(value, metadata.constraints[0]);
}

@@ -307,3 +309,3 @@ return true;

Validator.prototype.isDate = function (value) {
return value instanceof Date;
return value instanceof Date && !isNaN(value.getTime());
};

@@ -320,3 +322,3 @@ /**

Validator.prototype.isDateString = function (value) {
var regex = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+Z?/g;
var regex = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+[0-2]\d(?:\:[0-5]\d)?)?/g;
return this.isString(value) && regex.test(value);

@@ -339,6 +341,13 @@ };

/**
* Checks if a given value is a real number.
* Checks if a given value is a number.
*/
Validator.prototype.isNumber = function (value) {
return value instanceof Number || typeof value === "number";
Validator.prototype.isNumber = function (value, options) {
if (options === void 0) { options = {}; }
if (value === Infinity || value === -Infinity) {
return options.allowInfinity;
}
if (Number.isNaN(value)) {
return options.allowNaN;
}
return Number.isFinite(value);
};

@@ -349,6 +358,3 @@ /**

Validator.prototype.isInt = function (val) {
if (!this.isNumber(val))
return false;
var numberString = String(val); // fix it
return this.validatorJs.isInt(numberString);
return Number.isInteger(val);
};

@@ -722,2 +728,10 @@ // -------------------------------------------------------------------------

};
/**
* Checks if the value is an instance of the specified object.
*/
Validator.prototype.isInstance = function (object, targetTypeConstructor) {
return targetTypeConstructor
&& typeof targetTypeConstructor === "function"
&& object instanceof targetTypeConstructor;
};
return Validator;

@@ -724,0 +738,0 @@ }());

@@ -10,2 +10,12 @@ /**

/**
* If set to true validator will strip validated object of any properties that do not have any decorators.
*
* Tip: if no other decorator is suitable for your property use @Allow decorator.
*/
whitelist?: false;
/**
* If set to true, instead of stripping non-whitelisted properties validator will throw an error
*/
forbidNonWhitelisted?: false;
/**
* Groups to be used during validation of the object.

@@ -12,0 +22,0 @@ */

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc