From 1fbe4d8521b11c1df8c1a3271632f948ec920a5e Mon Sep 17 00:00:00 2001 From: Yogev Lahyani Date: Mon, 18 Mar 2019 12:06:27 +0200 Subject: [PATCH 1/2] IsObject & IsNotEmptyObject Decorators --- src/decorator/decorators.ts | 30 ++++++++ src/validation/ValidationTypes.ts | 6 ++ src/validation/Validator.ts | 29 ++++++++ ...alidation-functions-and-decorators.spec.ts | 70 +++++++++++++++++++ 4 files changed, 135 insertions(+) diff --git a/src/decorator/decorators.ts b/src/decorator/decorators.ts index 370bc7cd18..9022e003c9 100644 --- a/src/decorator/decorators.ts +++ b/src/decorator/decorators.ts @@ -828,6 +828,36 @@ export function IsJSON(validationOptions?: ValidationOptions) { }; } +/** + * Checks if the value is a valid object. + */ +export function IsObject(validationOptions?: ValidationOptions) { + return function (object: Object, propertyName: string) { + const args: ValidationMetadataArgs = { + type: ValidationTypes.IS_OBJECT, + target: object.constructor, + propertyName: propertyName, + validationOptions: validationOptions + }; + getFromContainer(MetadataStorage).addValidationMetadata(new ValidationMetadata(args)); + }; +} + +/** + * Checks if the value is a valid object & not empty. + */ +export function IsNotEmptyObject(validationOptions?: ValidationOptions) { + return function (object: Object, propertyName: string) { + const args: ValidationMetadataArgs = { + type: ValidationTypes.IS_NOT_EMPTY_OBJECT, + target: object.constructor, + propertyName: propertyName, + validationOptions: validationOptions + }; + getFromContainer(MetadataStorage).addValidationMetadata(new ValidationMetadata(args)); + }; +} + /** * Checks if the string is lowercase. */ diff --git a/src/validation/ValidationTypes.ts b/src/validation/ValidationTypes.ts index eb128cdfe9..763e0dee69 100644 --- a/src/validation/ValidationTypes.ts +++ b/src/validation/ValidationTypes.ts @@ -67,6 +67,8 @@ export class ValidationTypes { static IS_ISIN = "isIsin"; static IS_ISO8601 = "isIso8601"; static IS_JSON = "isJson"; + static IS_OBJECT = "isObject"; + static IS_NOT_EMPTY_OBJECT = "isNotEmptyObject"; static IS_LOWERCASE = "isLowercase"; static IS_MOBILE_PHONE = "isMobilePhone"; static IS_PHONE_NUMBER = "isPhoneNumber"; @@ -213,6 +215,10 @@ export class ValidationTypes { return eachPrefix + "$property must be a valid ISO 8601 date string"; case this.IS_JSON: return eachPrefix + "$property must be a json string"; + case this.IS_OBJECT: + return eachPrefix + "$property must be an object"; + case this.IS_NOT_EMPTY_OBJECT: + return eachPrefix + "$property must be a non-empty object"; case this.IS_LOWERCASE: return eachPrefix + "$property must be a lowercase string"; case this.IS_MOBILE_PHONE: diff --git a/src/validation/Validator.ts b/src/validation/Validator.ts index ff8ca18482..886147e328 100644 --- a/src/validation/Validator.ts +++ b/src/validation/Validator.ts @@ -19,6 +19,15 @@ export class Validator { private libPhoneNumber = { phoneUtil: require("google-libphonenumber").PhoneNumberUtil.getInstance(), }; + private _isEmptyObject = function(object: object) { + for (const key in object) { + if (object.hasOwnProperty(key)) { + return false; + } + } + + return true; + }; /** * Performs validation of the given object based on decorators or validation schema. @@ -210,6 +219,10 @@ export class Validator { return this.isISO8601(value); case ValidationTypes.IS_JSON: return this.isJSON(value); + case ValidationTypes.IS_OBJECT: + return this.isObject(value); + case ValidationTypes.IS_NOT_EMPTY_OBJECT: + return this.isNotEmptyObject(value); case ValidationTypes.IS_LOWERCASE: return this.isLowercase(value); case ValidationTypes.IS_MOBILE_PHONE: @@ -634,6 +647,22 @@ export class Validator { return typeof value === "string" && this.validatorJs.isJSON(value); } + /** + * Checks if the value is valid Object. + * Returns false if the value is not an object. + */ + isObject(value: any): boolean { + return value != null && (typeof value === "object" || typeof value === "function"); + } + + /** + * Checks if the value is valid Object & not empty. + * Returns false if the value is not an object or an empty valid object. + */ + isNotEmptyObject(value: any): boolean { + return this.isObject(value) && !this._isEmptyObject(value); + } + /** * Checks if the string is lowercase. * If given value is not a string, then it returns false. diff --git a/test/functional/validation-functions-and-decorators.spec.ts b/test/functional/validation-functions-and-decorators.spec.ts index 1d06a71d81..6264efd4a4 100644 --- a/test/functional/validation-functions-and-decorators.spec.ts +++ b/test/functional/validation-functions-and-decorators.spec.ts @@ -32,6 +32,8 @@ import { IsIn, IsInt, IsJSON, + IsObject, + IsNotEmptyObject, Length, IsLowercase, IsMongoId, @@ -2162,6 +2164,74 @@ describe("IsJSON", function() { }); +describe("IsObject", function() { + + const validValues = [{ "key": "value" }, { key: "value" }, {}]; + const invalidValues = [null, undefined, "{ key: \"value\" }", "{ 'key': 'value' }", "string", 1234, false]; + + class MyClass { + @IsObject() + someProperty: object; + } + + it("should not fail if validator.validate said that its valid", function(done) { + checkValidValues(new MyClass(), validValues, done); + }); + + it("should fail if validator.validate said that its invalid", function(done) { + checkInvalidValues(new MyClass(), invalidValues, done); + }); + + it("should not fail if method in validator said that its valid", function() { + validValues.forEach(value => validator.isObject(value).should.be.true); + }); + + it("should fail if method in validator said that its invalid", function() { + invalidValues.forEach(value => validator.isObject(value).should.be.false); + }); + + it("should return error object with proper data", function(done) { + const validationType = "isObject"; + const message = "someProperty must be an object"; + checkReturnedError(new MyClass(), invalidValues, validationType, message, done); + }); + +}); + +describe("IsNotEmptyObject", function() { + + const validValues = [{ "key": "value" }, { key: "value" }]; + const invalidValues = [null, undefined, "{ key: \"value\" }", "{ 'key': 'value' }", "string", 1234, false, {}]; + + class MyClass { + @IsNotEmptyObject() + someProperty: object; + } + + it("should not fail if validator.validate said that its valid", function(done) { + checkValidValues(new MyClass(), validValues, done); + }); + + it("should fail if validator.validate said that its invalid", function(done) { + checkInvalidValues(new MyClass(), invalidValues, done); + }); + + it("should not fail if method in validator said that its valid", function() { + validValues.forEach(value => validator.isNotEmptyObject(value).should.be.true); + }); + + it("should fail if method in validator said that its invalid", function() { + invalidValues.forEach(value => validator.isNotEmptyObject(value).should.be.false); + }); + + it("should return error object with proper data", function(done) { + const validationType = "isNotEmptyObject"; + const message = "someProperty must be a non-empty object"; + checkReturnedError(new MyClass(), invalidValues, validationType, message, done); + }); + +}); + describe("IsLowercase", function() { const validValues = [ From 909f20b30f16c6cea136d1114fe1b31af9097522 Mon Sep 17 00:00:00 2001 From: Yogev Lahyani Date: Sun, 28 Jul 2019 11:09:28 +0300 Subject: [PATCH 2/2] Add features to docs and improve test-cases and decorators --- README.md | 4 ++++ src/validation/Validator.ts | 2 +- test/functional/validation-functions-and-decorators.spec.ts | 4 ++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6f932dda15..c78e32dcf4 100644 --- a/README.md +++ b/README.md @@ -752,6 +752,8 @@ validator.isISBN(str, version); // Checks if the string is an ISBN (version 10 o validator.isISIN(str); // Checks if the string is an ISIN (stock/security identifier). validator.isISO8601(str); // Checks if the string is a valid ISO 8601 date. validator.isJSON(str); // Checks if the string is valid JSON (note: uses JSON.parse). +validator.isObject(object); // Checks if the object is valid Object (null, functions, arrays will return false) +validator.isNotEmptyObject(object); // Checks if the object is not empty validator.isLowercase(str); // Checks if the string is lowercase. validator.isMobilePhone(str, locale); // Checks if the string is a mobile phone number. validator.isPhoneNumber(str, region); // Checks if the string is a valid phone number. @@ -835,6 +837,8 @@ validator.isInstance(value, target); // Checks value is an instance of the targe | `@IsISIN()` | Checks if the string is an ISIN (stock/security identifier). | | `@IsISO8601()` | Checks if the string is a valid ISO 8601 date. | | `@IsJSON()` | Checks if the string is valid JSON. | +| `@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. | | `@IsMobilePhone(locale: string)` | Checks if the string is a mobile phone number. | | `@IsPhoneNumber(region: string)` | Checks if the string is a valid phone number. "region" accepts 2 characters uppercase country code (e.g. DE, US, CH).If users must enter the intl. prefix (e.g. +41), then you may pass "ZZ" or null as region. See [google-libphonenumber, metadata.js:countryCodeToRegionCodeMap on github](https://github.com/ruimarinho/google-libphonenumber/blob/1e46138878cff479aafe2ce62175c6c49cb58720/src/metadata.js#L33) | diff --git a/src/validation/Validator.ts b/src/validation/Validator.ts index 886147e328..aa77eb75a9 100644 --- a/src/validation/Validator.ts +++ b/src/validation/Validator.ts @@ -652,7 +652,7 @@ export class Validator { * Returns false if the value is not an object. */ isObject(value: any): boolean { - return value != null && (typeof value === "object" || typeof value === "function"); + return value != null && (typeof value === "object" || typeof value === "function") && !Array.isArray(value); } /** diff --git a/test/functional/validation-functions-and-decorators.spec.ts b/test/functional/validation-functions-and-decorators.spec.ts index 6264efd4a4..8bab4b8e8f 100644 --- a/test/functional/validation-functions-and-decorators.spec.ts +++ b/test/functional/validation-functions-and-decorators.spec.ts @@ -2167,7 +2167,7 @@ describe("IsJSON", function() { describe("IsObject", function() { const validValues = [{ "key": "value" }, { key: "value" }, {}]; - const invalidValues = [null, undefined, "{ key: \"value\" }", "{ 'key': 'value' }", "string", 1234, false]; + const invalidValues: any[] = [null, undefined, "{ key: \"value\" }", "{ 'key': 'value' }", "string", 1234, false, "[]", [], [{ key: "value" }]]; class MyClass { @IsObject() @@ -2201,7 +2201,7 @@ describe("IsObject", function() { describe("IsNotEmptyObject", function() { const validValues = [{ "key": "value" }, { key: "value" }]; - const invalidValues = [null, undefined, "{ key: \"value\" }", "{ 'key': 'value' }", "string", 1234, false, {}]; + const invalidValues = [null, undefined, "{ key: \"value\" }", "{ 'key': 'value' }", "string", 1234, false, {}, [], [{ key: "value" }]]; class MyClass { @IsNotEmptyObject()