Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ validator.arrayUnique(array); // Checks if all array's values are unique. Compar
| `@MaxDate(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"). |
| `@IsDateString()` | Checks if a string is a date. |
| `@IsDateString()` | Checks if a string is a date (e.g. "2017-06-07T14:34:08.700Z" or "2017-06-07T14:34:08.700"). |
| `@IsNumberString()` | Checks if a string is a number. |
| **String validation decorators** |
| `@Contains(seed: string)` | Checks if the string contains the seed. |
Expand Down
18 changes: 15 additions & 3 deletions src/decorator/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ export function ValidatorConstraint(options?: { name?: string, async?: boolean }
const metadata = new ConstraintMetadata(target, name, isAsync);
getFromContainer(MetadataStorage).addConstraintMetadata(metadata);
};
}
}

/**
* Performs validation based on the given custom validation class.
* Performs validation based on the given custom validation class.
* Validation class must be decorated with ValidatorConstraint decorator.
*/
export function Validate(constraintClass: Function, validationOptions?: ValidationOptions): Function;
Expand Down Expand Up @@ -271,6 +271,18 @@ export function IsString(validationOptions?: ValidationOptions) {
};
}

export function IsDateString(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
const args: ValidationMetadataArgs = {
type: ValidationTypes.IS_DATE_STRING,
target: object.constructor,
propertyName: propertyName,
validationOptions: validationOptions
};
getFromContainer(MetadataStorage).addValidationMetadata(new ValidationMetadata(args));
};
}

/**
* Checks if a value is an array.
*/
Expand Down Expand Up @@ -979,7 +991,7 @@ export function Matches(pattern: RegExp, modifiersOrAnnotationOptions?: string|V
}

/**
* Checks if the string correctly represents a time in the format HH:MM
* Checks if the string correctly represents a time in the format HH:MM
*/
export function IsMilitaryTime(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
Expand Down
13 changes: 8 additions & 5 deletions src/validation/ValidationTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {ValidationArguments} from "./ValidationArguments";
* Validation types.
*/
export class ValidationTypes {

/* system */
static CUSTOM_VALIDATION = "customValidation";
static NESTED_VALIDATION = "nestedValidation";
Expand All @@ -24,6 +24,7 @@ export class ValidationTypes {
static IS_DATE = "isDate";
static IS_NUMBER = "isNumber";
static IS_STRING = "isString";
static IS_DATE_STRING = "isDateString";
static IS_ARRAY = "isArray";
static IS_INT = "isInt";
static IS_ENUM = "isEnum";
Expand Down Expand Up @@ -92,8 +93,8 @@ export class ValidationTypes {
*/
static isValid(type: string) {
return type !== "isValid" &&
type !== "getMessage" &&
Object.keys(this).map(key => (this as any)[key]).indexOf(type) !== -1;
type !== "getMessage" &&
Object.keys(this).map(key => (this as any)[key]).indexOf(type) !== -1;
}

/**
Expand Down Expand Up @@ -130,6 +131,8 @@ export class ValidationTypes {
return eachPrefix + "$property must be an integer number";
case this.IS_STRING:
return eachPrefix + "$property must be a string";
case this.IS_DATE_STRING:
return eachPrefix + "$property must be a ISOString";
case this.IS_ARRAY:
return eachPrefix + "$property must be an array";
case this.IS_ENUM:
Expand Down Expand Up @@ -250,8 +253,8 @@ export class ValidationTypes {
case this.ARRAY_UNIQUE:
return eachPrefix + "All $property's elements must be unique";
}

return "";
}

}
32 changes: 21 additions & 11 deletions src/validation/Validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export class Validator {
if (errors.length)
return Promise.reject(errors);
}

/**
* Performs validation of the given object based on decorators used in given object class.
* NOTE: This method completely ignores all async validations.
Expand Down Expand Up @@ -129,6 +129,8 @@ export class Validator {
return this.isDate(value);
case ValidationTypes.IS_STRING:
return this.isString(value);
case ValidationTypes.IS_DATE_STRING:
return this.isDateString(value);
case ValidationTypes.IS_ARRAY:
return this.isArray(value);
case ValidationTypes.IS_NUMBER:
Expand Down Expand Up @@ -327,14 +329,22 @@ export class Validator {
return value instanceof String || typeof value === "string";
}

/**
* Checks if a given value is a ISOString date.
*/
isDateString(value: any): boolean {
const regex = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+Z?/g;
return this.isString(value) && regex.test(value);
}

/**
* Checks if a given value is an array
*/
isArray(value: any): boolean {
return value instanceof Array;
}

/**
/**
* Checks if a given value is an enum
*/
isEnum(value: any, entity: any): boolean {
Expand Down Expand Up @@ -370,9 +380,9 @@ export class Validator {
* Checks if value is a number that's divisible by another.
*/
isDivisibleBy(value: number, num: number): boolean {
return typeof value === "number" &&
typeof num === "number" &&
this.validatorJs.isDivisibleBy(String(value), num);
return typeof value === "number" &&
typeof num === "number" &&
this.validatorJs.isDivisibleBy(String(value), num);
}

/**
Expand Down Expand Up @@ -717,7 +727,7 @@ export class Validator {
isMilitaryTime(value: string): boolean {
return this.matches(value, /^([01]\d|2[0-3]):?([0-5]\d)$/);
}

// -------------------------------------------------------------------------
// Validation Methods: array checkers
// -------------------------------------------------------------------------
Expand All @@ -729,7 +739,7 @@ export class Validator {
arrayContains(array: any[], values: any[]) {
if (!(array instanceof Array))
return false;

return !array || values.every(value => array.indexOf(value) !== -1);
}

Expand All @@ -740,7 +750,7 @@ export class Validator {
arrayNotContains(array: any[], values: any[]) {
if (!(array instanceof Array))
return false;

return !array || values.every(value => array.indexOf(value) === -1);
}

Expand All @@ -751,7 +761,7 @@ export class Validator {
arrayNotEmpty(array: any[]) {
if (!(array instanceof Array))
return false;

return array instanceof Array && array.length > 0;
}

Expand All @@ -762,7 +772,7 @@ export class Validator {
arrayMinSize(array: any[], min: number) {
if (!(array instanceof Array))
return false;

return array instanceof Array && array.length >= min;
}

Expand All @@ -773,7 +783,7 @@ export class Validator {
arrayMaxSize(array: any[], max: number) {
if (!(array instanceof Array))
return false;

return array instanceof Array && array.length <= max;
}

Expand Down
59 changes: 51 additions & 8 deletions test/functional/validation-functions-and-decorators.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ import {
ArrayContains,
ArrayNotContains,
ArrayUnique,
IsArray
IsArray,
IsDateString
} from "../../src/decorator/decorators";
import {Validator} from "../../src/validation/Validator";
import {ValidatorOptions} from "../../src/validation/ValidatorOptions";
Expand Down Expand Up @@ -566,6 +567,48 @@ describe("IsString", function() {

});

describe("IsDateString", function() {

const validValues = ["2017-06-06T17:04:42.081Z", "2017-06-06T17:04:42.081"];
const invalidValues = [
true,
false,
1,
2,
null,
undefined,
"text"
];

class MyClass {
@IsDateString()
someProperty: string;
}

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 => expect(validator.isDateString(value)).be.true);
});

it("should fail if method in validator said that its invalid", function() {
invalidValues.forEach(value => expect(validator.isDateString(value as any)).be.false);
});

it("should return error object with proper data", function(done) {
const validationType = "isDateString";
const message = "someProperty deve ser um texto de data";
checkReturnedError(new MyClass(), invalidValues, validationType, message, done);
});

});

describe("IsArray", function() {

const validValues = [[], [1, 2, 3], [0, 0, 0], [""], [0], [undefined], [{}], new Array()];
Expand Down Expand Up @@ -1049,7 +1092,7 @@ describe("IsNumberString", function() {
// -------------------------------------------------------------------------

describe("Contains", function() {

const constraint = "hello";
const validValues = ["hello world"];
const invalidValues = [null, undefined, "bye world"];
Expand Down Expand Up @@ -1084,7 +1127,7 @@ describe("Contains", function() {
});

describe("NotContains", function() {

const constraint = "hello";
const validValues = ["bye world"];
const invalidValues = [null, undefined, "hello world"];
Expand Down Expand Up @@ -1295,9 +1338,9 @@ describe("IsByteLength", function() {
});

describe("IsCreditCard", function() {

const validValues = [
"375556917985515",
"375556917985515",
"36050234196908",
"4716461583322103",
"4716-2210-5188-5662",
Expand Down Expand Up @@ -1336,7 +1379,7 @@ describe("IsCreditCard", function() {
});

describe("IsCurrency", function() {

const validValues = [
"-$10,123.45"
, "$10,123.45"
Expand Down Expand Up @@ -2514,7 +2557,7 @@ describe("IsUppercase", function() {
, " ."
];
const invalidValues = [
null,
null,
undefined,
"fooBar",
"123abc"
Expand Down Expand Up @@ -2895,7 +2938,7 @@ describe("ArrayMaxSize", function() {
const message = "someProperty must contain not more than " + constraint + " elements";
checkReturnedError(new MyClass(), invalidValues, validationType, message, done);
});

});

describe("ArrayUnique", function() {
Expand Down