This commit is contained in:
Pipi Chen
2020-05-07 01:02:44 +08:00
commit b8a3516cd6
2147 changed files with 184854 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
//# sourceMappingURL=ValidationArguments.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/validation/ValidationArguments.ts"],"names":[],"mappings":"","file":"ValidationArguments.js","sourcesContent":["/**\n * Arguments being sent to message builders - user can create message either by simply returning a string,\n * either by returning a function that accepts MessageArguments and returns a message string built based on these arguments.\n */\nexport interface ValidationArguments {\n\n /**\n * Validating value.\n */\n value: any;\n\n /**\n * Constraints set by this validation type.\n */\n constraints: any[];\n\n /**\n * Name of the target that is being validated.\n */\n targetName: string;\n\n /**\n * Object that is being validated.\n */\n object: Object;\n\n /**\n * Name of the object's property being validated.\n */\n property: string;\n \n}"],"sourceRoot":".."}

View File

@@ -0,0 +1,45 @@
/**
* Validation error description.
*/
var ValidationError = /** @class */ (function () {
function ValidationError() {
}
/**
*
* @param shouldDecorate decorate the message with ANSI formatter escape codes for better readability
* @param hasParent true when the error is a child of an another one
* @param parentPath path as string to the parent of this property
*/
ValidationError.prototype.toString = function (shouldDecorate, hasParent, parentPath) {
var _this = this;
if (shouldDecorate === void 0) { shouldDecorate = false; }
if (hasParent === void 0) { hasParent = false; }
if (parentPath === void 0) { parentPath = ""; }
var boldStart = shouldDecorate ? "\u001B[1m" : "";
var boldEnd = shouldDecorate ? "\u001B[22m" : "";
var propConstraintFailed = function (propertyName) { return " - property " + boldStart + parentPath + propertyName + boldEnd + " has failed the following constraints: " + boldStart + Object.keys(_this.constraints).join(", ") + boldEnd + " \n"; };
if (!hasParent) {
return "An instance of " + boldStart + (this.target ? this.target.constructor.name : "an object") + boldEnd + " has failed the validation:\n" +
(this.constraints ? propConstraintFailed(this.property) : "") +
this.children
.map(function (childError) { return childError.toString(shouldDecorate, true, _this.property); })
.join("");
}
else {
// we format numbers as array indexes for better readability.
var formattedProperty_1 = Number.isInteger(+this.property) ? "[" + this.property + "]" : "" + (parentPath ? "." : "") + this.property;
if (this.constraints) {
return propConstraintFailed(formattedProperty_1);
}
else {
return this.children
.map(function (childError) { return childError.toString(shouldDecorate, true, "" + parentPath + formattedProperty_1); })
.join("");
}
}
};
return ValidationError;
}());
export { ValidationError };
//# sourceMappingURL=ValidationError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/validation/ValidationError.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH;IAAA;IAuEA,CAAC;IA9BG;;;;;OAKG;IACH,kCAAQ,GAAR,UAAS,cAA+B,EAAE,SAA0B,EAAE,UAAuB;QAA7F,iBAuBC;QAvBQ,+BAAA,EAAA,sBAA+B;QAAE,0BAAA,EAAA,iBAA0B;QAAE,2BAAA,EAAA,eAAuB;QACzF,IAAM,SAAS,GAAG,cAAc,CAAC,CAAC,CAAC,WAAS,CAAC,CAAC,CAAC,EAAE,CAAC;QAClD,IAAM,OAAO,GAAG,cAAc,CAAC,CAAC,CAAC,YAAU,CAAC,CAAC,CAAC,EAAE,CAAC;QACjD,IAAM,oBAAoB,GAAG,UAAC,YAAoB,IAAa,OAAA,iBAAe,SAAS,GAAG,UAAU,GAAG,YAAY,GAAG,OAAO,+CAA0C,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,KAAI,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,OAAO,QAAK,EAA3K,CAA2K,CAAC;QAE3O,IAAI,CAAC,SAAS,EAAE;YACZ,OAAO,oBAAkB,SAAS,IAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,IAAG,OAAO,kCAA+B;gBAClI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,oBAAoB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC7D,IAAI,CAAC,QAAQ;qBACR,GAAG,CAAC,UAAA,UAAU,IAAI,OAAA,UAAU,CAAC,QAAQ,CAAC,cAAc,EAAE,IAAI,EAAE,KAAI,CAAC,QAAQ,CAAC,EAAxD,CAAwD,CAAC;qBAC3E,IAAI,CAAC,EAAE,CAAC,CAAC;SACrB;aAAM;YACH,6DAA6D;YAC7D,IAAM,mBAAiB,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAI,IAAI,CAAC,QAAQ,MAAG,CAAC,CAAC,CAAC,MAAG,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,IAAG,IAAI,CAAC,QAAU,CAAC;YAE/H,IAAI,IAAI,CAAC,WAAW,EAAE;gBAClB,OAAO,oBAAoB,CAAC,mBAAiB,CAAC,CAAC;aAClD;iBAAM;gBACH,OAAO,IAAI,CAAC,QAAQ;qBACf,GAAG,CAAC,UAAA,UAAU,IAAI,OAAA,UAAU,CAAC,QAAQ,CAAC,cAAc,EAAE,IAAI,EAAE,KAAG,UAAU,GAAG,mBAAmB,CAAG,EAAhF,CAAgF,CAAC;qBACnG,IAAI,CAAC,EAAE,CAAC,CAAC;aACjB;SACJ;IACL,CAAC;IACL,sBAAC;AAAD,CAvEA,AAuEC,IAAA","file":"ValidationError.js","sourcesContent":["/**\n * Validation error description.\n */\nexport class ValidationError {\n\n /**\n * Object that was validated.\n *\n * OPTIONAL - configurable via the ValidatorOptions.validationError.target option\n */\n target?: Object;\n\n /**\n * Object's property that haven't pass validation.\n */\n property: string;\n\n /**\n * Value that haven't pass a validation.\n *\n * OPTIONAL - configurable via the ValidatorOptions.validationError.value option\n */\n value?: any;\n\n /**\n * Constraints that failed validation with error messages.\n */\n constraints?: {\n [type: string]: string\n };\n\n /**\n * Contains all nested validation errors of the property.\n */\n children: ValidationError[];\n\n\n /*\n * A transient set of data passed through to the validation result for response mapping\n */\n contexts?: {\n [type: string]: any\n };\n\n /**\n *\n * @param shouldDecorate decorate the message with ANSI formatter escape codes for better readability\n * @param hasParent true when the error is a child of an another one\n * @param parentPath path as string to the parent of this property\n */\n toString(shouldDecorate: boolean = false, hasParent: boolean = false, parentPath: string = ``): string {\n const boldStart = shouldDecorate ? `\\x1b[1m` : ``;\n const boldEnd = shouldDecorate ? `\\x1b[22m` : ``;\n const propConstraintFailed = (propertyName: string): string => ` - property ${boldStart}${parentPath}${propertyName}${boldEnd} has failed the following constraints: ${boldStart}${Object.keys(this.constraints).join(`, `)}${boldEnd} \\n`;\n\n if (!hasParent) {\n return `An instance of ${boldStart}${this.target ? this.target.constructor.name : \"an object\"}${boldEnd} has failed the validation:\\n` +\n (this.constraints ? propConstraintFailed(this.property) : ``) +\n this.children\n .map(childError => childError.toString(shouldDecorate, true, this.property))\n .join(``);\n } else {\n // we format numbers as array indexes for better readability.\n const formattedProperty = Number.isInteger(+this.property) ? `[${this.property}]` : `${parentPath ? `.` : ``}${this.property}`;\n\n if (this.constraints) {\n return propConstraintFailed(formattedProperty);\n } else {\n return this.children\n .map(childError => childError.toString(shouldDecorate, true, `${parentPath}${formattedProperty}`, ))\n .join(``);\n }\n }\n }\n}\n"],"sourceRoot":".."}

View File

@@ -0,0 +1,326 @@
import { ValidationError } from "./ValidationError";
import { ValidationTypes } from "./ValidationTypes";
import { ValidationUtils } from "./ValidationUtils";
import { isPromise, convertToArray } from "../utils";
import { getMetadataStorage } from "../metadata/MetadataStorage";
/**
* Executes validation over given object.
*/
var ValidationExecutor = /** @class */ (function () {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
function ValidationExecutor(validator, validatorOptions) {
this.validator = validator;
this.validatorOptions = validatorOptions;
// -------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------
this.awaitingPromises = [];
this.ignoreAsyncValidations = false;
// -------------------------------------------------------------------------
// Private Properties
// -------------------------------------------------------------------------
this.metadataStorage = getMetadataStorage();
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
ValidationExecutor.prototype.execute = function (object, targetSchema, validationErrors) {
var _this = this;
/**
* If there is no metadata registered it means possibly the dependencies are not flatterned and
* more than one instance is used.
*
* TODO: This needs proper handling, forcing to use the same container or some other proper solution.
*/
if (!this.metadataStorage.hasValidationMetaData) {
console.warn("No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies.");
}
var groups = this.validatorOptions ? this.validatorOptions.groups : undefined;
var targetMetadatas = this.metadataStorage.getTargetValidationMetadatas(object.constructor, targetSchema, groups);
var groupedMetadatas = this.metadataStorage.groupByPropertyName(targetMetadatas);
if (this.validatorOptions && this.validatorOptions.forbidUnknownValues && !targetMetadatas.length) {
var validationError = new ValidationError();
if (!this.validatorOptions ||
!this.validatorOptions.validationError ||
this.validatorOptions.validationError.target === undefined ||
this.validatorOptions.validationError.target === true)
validationError.target = object;
validationError.value = undefined;
validationError.property = undefined;
validationError.children = [];
validationError.constraints = { unknownValue: "an unknown value was passed to the validate function" };
validationErrors.push(validationError);
return;
}
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.IS_DEFINED; });
var metadatas = groupedMetadatas[propertyName].filter(function (metadata) { return metadata.type !== ValidationTypes.IS_DEFINED && metadata.type !== ValidationTypes.WHITELIST; });
if (value instanceof Promise && metadatas.find(function (metadata) { return metadata.type === ValidationTypes.PROMISE_VALIDATION; })) {
_this.awaitingPromises.push(value.then(function (resolvedValue) {
_this.performValidations(object, resolvedValue, propertyName, definedMetadatas, metadatas, validationErrors);
}));
}
else {
_this.performValidations(object, value, propertyName, definedMetadatas, metadatas, validationErrors);
}
});
};
ValidationExecutor.prototype.whitelist = function (object, groupedMetadatas, validationErrors) {
var _this = this;
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) {
var _a;
var validationError = _this.generateValidationError(object, object[property], property);
validationError.constraints = (_a = {}, _a[ValidationTypes.WHITELIST] = "property " + property + " should not exist", _a);
validationError.children = undefined;
validationErrors.push(validationError);
});
}
else {
// strip non allowed properties
notAllowedProperties.forEach(function (property) { return delete object[property]; });
}
}
};
ValidationExecutor.prototype.stripEmptyErrors = function (errors) {
var _this = this;
return errors.filter(function (error) {
if (error.children) {
error.children = _this.stripEmptyErrors(error.children);
}
if (Object.keys(error.constraints).length === 0) {
if (error.children.length === 0) {
return false;
}
else {
delete error.constraints;
}
}
return true;
});
};
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
ValidationExecutor.prototype.performValidations = function (object, value, propertyName, definedMetadatas, metadatas, validationErrors) {
var customValidationMetadatas = metadatas.filter(function (metadata) { return metadata.type === ValidationTypes.CUSTOM_VALIDATION; });
var nestedValidationMetadatas = metadatas.filter(function (metadata) { return metadata.type === ValidationTypes.NESTED_VALIDATION; });
var conditionalValidationMetadatas = metadatas.filter(function (metadata) { return metadata.type === ValidationTypes.CONDITIONAL_VALIDATION; });
var validationError = this.generateValidationError(object, value, propertyName);
validationErrors.push(validationError);
var canValidate = this.conditionalValidations(object, value, conditionalValidationMetadatas);
if (!canValidate) {
return;
}
// handle IS_DEFINED validation type the special way - it should work no matter skipUndefinedProperties/skipMissingProperties is set or not
this.customValidations(object, value, definedMetadatas, validationError);
this.mapContexts(object, value, definedMetadatas, validationError);
if (value === undefined && this.validatorOptions && this.validatorOptions.skipUndefinedProperties === true) {
return;
}
if (value === null && this.validatorOptions && this.validatorOptions.skipNullProperties === true) {
return;
}
if ((value === null || value === undefined) && this.validatorOptions && this.validatorOptions.skipMissingProperties === true) {
return;
}
this.customValidations(object, value, customValidationMetadatas, validationError);
this.nestedValidations(value, nestedValidationMetadatas, validationError.children);
this.mapContexts(object, value, metadatas, validationError);
this.mapContexts(object, value, customValidationMetadatas, validationError);
};
ValidationExecutor.prototype.generateValidationError = function (object, value, propertyName) {
var validationError = new ValidationError();
if (!this.validatorOptions ||
!this.validatorOptions.validationError ||
this.validatorOptions.validationError.target === undefined ||
this.validatorOptions.validationError.target === true)
validationError.target = object;
if (!this.validatorOptions ||
!this.validatorOptions.validationError ||
this.validatorOptions.validationError.value === undefined ||
this.validatorOptions.validationError.value === true)
validationError.value = value;
validationError.property = propertyName;
validationError.children = [];
validationError.constraints = {};
return validationError;
};
ValidationExecutor.prototype.conditionalValidations = function (object, value, metadatas) {
return metadatas
.map(function (metadata) { return metadata.constraints[0](object, value); })
.reduce(function (resultA, resultB) { return resultA && resultB; }, true);
};
ValidationExecutor.prototype.customValidations = function (object, value, metadatas, error) {
var _this = this;
metadatas.forEach(function (metadata) {
_this.metadataStorage
.getTargetValidatorConstraints(metadata.constraintCls)
.forEach(function (customConstraintMetadata) {
if (customConstraintMetadata.async && _this.ignoreAsyncValidations)
return;
var validationArguments = {
targetName: object.constructor ? object.constructor.name : undefined,
property: metadata.propertyName,
object: object,
value: value,
constraints: metadata.constraints
};
if (!metadata.each || !(value instanceof Array || value instanceof Set || value instanceof Map)) {
var validatedValue = customConstraintMetadata.instance.validate(value, validationArguments);
if (isPromise(validatedValue)) {
var promise = validatedValue.then(function (isValid) {
if (!isValid) {
var _a = _this.createValidationError(object, value, metadata, customConstraintMetadata), type = _a[0], message = _a[1];
error.constraints[type] = message;
if (metadata.context) {
if (!error.contexts) {
error.contexts = {};
}
error.contexts[type] = Object.assign((error.contexts[type] || {}), metadata.context);
}
}
});
_this.awaitingPromises.push(promise);
}
else {
if (!validatedValue) {
var _a = _this.createValidationError(object, value, metadata, customConstraintMetadata), type = _a[0], message = _a[1];
error.constraints[type] = message;
}
}
return;
}
// convert set and map into array
var arrayValue = convertToArray(value);
// Validation needs to be applied to each array item
var validatedSubValues = arrayValue.map(function (subValue) { return customConstraintMetadata.instance.validate(subValue, validationArguments); });
var validationIsAsync = validatedSubValues
.some(function (validatedSubValue) { return isPromise(validatedSubValue); });
if (validationIsAsync) {
// Wrap plain values (if any) in promises, so that all are async
var asyncValidatedSubValues = validatedSubValues
.map(function (validatedSubValue) { return isPromise(validatedSubValue) ? validatedSubValue : Promise.resolve(validatedSubValue); });
var asyncValidationIsFinishedPromise = Promise.all(asyncValidatedSubValues)
.then(function (flatValidatedValues) {
var validationResult = flatValidatedValues.every(function (isValid) { return isValid; });
if (!validationResult) {
var _a = _this.createValidationError(object, value, metadata, customConstraintMetadata), type = _a[0], message = _a[1];
error.constraints[type] = message;
if (metadata.context) {
if (!error.contexts) {
error.contexts = {};
}
error.contexts[type] = Object.assign((error.contexts[type] || {}), metadata.context);
}
}
});
_this.awaitingPromises.push(asyncValidationIsFinishedPromise);
return;
}
var validationResult = validatedSubValues.every(function (isValid) { return isValid; });
if (!validationResult) {
var _b = _this.createValidationError(object, value, metadata, customConstraintMetadata), type = _b[0], message = _b[1];
error.constraints[type] = message;
}
});
});
};
ValidationExecutor.prototype.nestedValidations = function (value, metadatas, errors) {
var _this = this;
if (value === void 0) {
return;
}
metadatas.forEach(function (metadata) {
var _a;
if (metadata.type !== ValidationTypes.NESTED_VALIDATION &&
metadata.type !== ValidationTypes.PROMISE_VALIDATION) {
return;
}
if (value instanceof Array || value instanceof Set || value instanceof Map) {
// Treats Set as an array - as index of Set value is value itself and it is common case to have Object as value
var arrayLikeValue = value instanceof Set ? Array.from(value) : value;
arrayLikeValue.forEach(function (subValue, index) {
_this.performValidations(value, subValue, index.toString(), [], metadatas, errors);
});
}
else if (value instanceof Object) {
var targetSchema = typeof metadata.target === "string" ? metadata.target : metadata.target.name;
_this.execute(value, targetSchema, errors);
}
else {
var error = new ValidationError();
error.value = value;
error.property = metadata.propertyName;
error.target = metadata.target;
var _b = _this.createValidationError(metadata.target, value, metadata), type = _b[0], message = _b[1];
error.constraints = (_a = {},
_a[type] = message,
_a);
errors.push(error);
}
});
};
ValidationExecutor.prototype.mapContexts = function (object, value, metadatas, error) {
var _this = this;
return metadatas
.forEach(function (metadata) {
if (metadata.context) {
var customConstraint = void 0;
if (metadata.type === ValidationTypes.CUSTOM_VALIDATION) {
var customConstraints = _this.metadataStorage.getTargetValidatorConstraints(metadata.constraintCls);
customConstraint = customConstraints[0];
}
var type = _this.getConstraintType(metadata, customConstraint);
if (error.constraints[type]) {
if (!error.contexts) {
error.contexts = {};
}
error.contexts[type] = Object.assign((error.contexts[type] || {}), metadata.context);
}
}
});
};
ValidationExecutor.prototype.createValidationError = function (object, value, metadata, customValidatorMetadata) {
var targetName = object.constructor ? object.constructor.name : undefined;
var type = this.getConstraintType(metadata, customValidatorMetadata);
var validationArguments = {
targetName: targetName,
property: metadata.propertyName,
object: object,
value: value,
constraints: metadata.constraints
};
var message = metadata.message || "";
if (!metadata.message &&
(!this.validatorOptions || (this.validatorOptions && !this.validatorOptions.dismissDefaultMessages))) {
if (customValidatorMetadata && customValidatorMetadata.instance.defaultMessage instanceof Function) {
message = customValidatorMetadata.instance.defaultMessage(validationArguments);
}
}
var messageString = ValidationUtils.replaceMessageSpecialTokens(message, validationArguments);
return [type, messageString];
};
ValidationExecutor.prototype.getConstraintType = function (metadata, customValidatorMetadata) {
var type = customValidatorMetadata && customValidatorMetadata.name ? customValidatorMetadata.name : metadata.type;
return type;
};
return ValidationExecutor;
}());
export { ValidationExecutor };
//# sourceMappingURL=ValidationExecutor.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
/**
* Validation types.
*/
var ValidationTypes = /** @class */ (function () {
function ValidationTypes() {
}
/**
* Checks if validation type is valid.
*/
ValidationTypes.isValid = function (type) {
var _this = this;
return type !== "isValid" &&
type !== "getMessage" &&
Object.keys(this).map(function (key) { return _this[key]; }).indexOf(type) !== -1;
};
/* system */
ValidationTypes.CUSTOM_VALIDATION = "customValidation"; // done
ValidationTypes.NESTED_VALIDATION = "nestedValidation"; // done
ValidationTypes.PROMISE_VALIDATION = "promiseValidation"; // done
ValidationTypes.CONDITIONAL_VALIDATION = "conditionalValidation"; // done
ValidationTypes.WHITELIST = "whitelistValidation"; // done
ValidationTypes.IS_DEFINED = "isDefined"; // done
return ValidationTypes;
}());
export { ValidationTypes };
//# sourceMappingURL=ValidationTypes.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/validation/ValidationTypes.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH;IAAA;IAmBA,CAAC;IATG;;OAEG;IACI,uBAAO,GAAd,UAAe,IAAY;QAA3B,iBAIC;QAHG,OAAO,IAAI,KAAK,SAAS;YACrB,IAAI,KAAK,YAAY;YACrB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,UAAA,GAAG,IAAI,OAAC,KAAY,CAAC,GAAG,CAAC,EAAlB,CAAkB,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IAC9E,CAAC;IAfD,YAAY;IACL,iCAAiB,GAAG,kBAAkB,CAAC,CAAC,OAAO;IAC/C,iCAAiB,GAAG,kBAAkB,CAAC,CAAC,OAAO;IAC/C,kCAAkB,GAAG,mBAAmB,CAAC,CAAC,OAAO;IACjD,sCAAsB,GAAG,uBAAuB,CAAC,CAAC,OAAO;IACzD,yBAAS,GAAG,qBAAqB,CAAC,CAAC,OAAO;IAC1C,0BAAU,GAAG,WAAW,CAAC,CAAC,OAAO;IAW5C,sBAAC;CAnBD,AAmBC,IAAA;SAnBY,eAAe","file":"ValidationTypes.js","sourcesContent":["/**\n * Validation types.\n */\nexport class ValidationTypes {\n\n /* system */\n static CUSTOM_VALIDATION = \"customValidation\"; // done\n static NESTED_VALIDATION = \"nestedValidation\"; // done\n static PROMISE_VALIDATION = \"promiseValidation\"; // done\n static CONDITIONAL_VALIDATION = \"conditionalValidation\"; // done\n static WHITELIST = \"whitelistValidation\"; // done\n static IS_DEFINED = \"isDefined\"; // done\n\n /**\n * Checks if validation type is valid.\n */\n static isValid(type: string) {\n return type !== \"isValid\" &&\n type !== \"getMessage\" &&\n Object.keys(this).map(key => (this as any)[key]).indexOf(type) !== -1;\n }\n\n}\n"],"sourceRoot":".."}

View File

@@ -0,0 +1,29 @@
var ValidationUtils = /** @class */ (function () {
function ValidationUtils() {
}
ValidationUtils.replaceMessageSpecialTokens = function (message, validationArguments) {
var messageString;
if (message instanceof Function) {
messageString = message(validationArguments);
}
else if (typeof message === "string") {
messageString = message;
}
if (messageString && validationArguments.constraints instanceof Array) {
validationArguments.constraints.forEach(function (constraint, index) {
messageString = messageString.replace(new RegExp("\\$constraint" + (index + 1), "g"), constraint);
});
}
if (messageString && validationArguments.value !== undefined && validationArguments.value !== null && typeof validationArguments.value === "string")
messageString = messageString.replace(/\$value/g, validationArguments.value);
if (messageString)
messageString = messageString.replace(/\$property/g, validationArguments.property);
if (messageString)
messageString = messageString.replace(/\$target/g, validationArguments.targetName);
return messageString;
};
return ValidationUtils;
}());
export { ValidationUtils };
//# sourceMappingURL=ValidationUtils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/validation/ValidationUtils.ts"],"names":[],"mappings":"AAEA;IAAA;IA6BA,CAAC;IA3BU,2CAA2B,GAAlC,UAAmC,OAAuD,EAC9D,mBAAwC;QAEhE,IAAI,aAAqB,CAAC;QAC1B,IAAI,OAAO,YAAY,QAAQ,EAAE;YAC7B,aAAa,GAAI,OAAiD,CAAC,mBAAmB,CAAC,CAAC;SAE3F;aAAM,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YACpC,aAAa,GAAG,OAAiB,CAAC;SACrC;QAED,IAAI,aAAa,IAAI,mBAAmB,CAAC,WAAW,YAAY,KAAK,EAAE;YACnE,mBAAmB,CAAC,WAAW,CAAC,OAAO,CAAC,UAAC,UAAU,EAAE,KAAK;gBACtD,aAAa,GAAG,aAAa,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,mBAAgB,KAAK,GAAG,CAAC,CAAE,EAAE,GAAG,CAAC,EAAE,UAAU,CAAC,CAAC;YACpG,CAAC,CAAC,CAAC;SACN;QAED,IAAI,aAAa,IAAI,mBAAmB,CAAC,KAAK,KAAK,SAAS,IAAI,mBAAmB,CAAC,KAAK,KAAK,IAAI,IAAI,OAAO,mBAAmB,CAAC,KAAK,KAAK,QAAQ;YAC/I,aAAa,GAAG,aAAa,CAAC,OAAO,CAAC,UAAU,EAAE,mBAAmB,CAAC,KAAK,CAAC,CAAC;QACjF,IAAI,aAAa;YACb,aAAa,GAAG,aAAa,CAAC,OAAO,CAAC,aAAa,EAAE,mBAAmB,CAAC,QAAQ,CAAC,CAAC;QACvF,IAAI,aAAa;YACb,aAAa,GAAG,aAAa,CAAC,OAAO,CAAC,WAAW,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC;QAEvF,OAAO,aAAa,CAAC;IACzB,CAAC;IAEL,sBAAC;AAAD,CA7BA,AA6BC,IAAA","file":"ValidationUtils.js","sourcesContent":["import {ValidationArguments} from \"./ValidationArguments\";\n\nexport class ValidationUtils {\n\n static replaceMessageSpecialTokens(message: string|((args: ValidationArguments) => string),\n validationArguments: ValidationArguments): string {\n\n let messageString: string;\n if (message instanceof Function) {\n messageString = (message as (args: ValidationArguments) => string)(validationArguments);\n\n } else if (typeof message === \"string\") {\n messageString = message as string;\n }\n\n if (messageString && validationArguments.constraints instanceof Array) {\n validationArguments.constraints.forEach((constraint, index) => {\n messageString = messageString.replace(new RegExp(`\\\\$constraint${index + 1}`, \"g\"), constraint);\n });\n }\n\n if (messageString && validationArguments.value !== undefined && validationArguments.value !== null && typeof validationArguments.value === \"string\")\n messageString = messageString.replace(/\\$value/g, validationArguments.value);\n if (messageString)\n messageString = messageString.replace(/\\$property/g, validationArguments.property);\n if (messageString)\n messageString = messageString.replace(/\\$target/g, validationArguments.targetName);\n\n return messageString;\n }\n \n}"],"sourceRoot":".."}

View File

@@ -0,0 +1,68 @@
import * as tslib_1 from "tslib";
import { ValidationExecutor } from "./ValidationExecutor";
/**
* Validator performs validation of the given object based on its metadata.
*/
var Validator = /** @class */ (function () {
function Validator() {
}
// -------------------------------------------------------------------------
// Private Properties
// -------------------------------------------------------------------------
/**
* Performs validation of the given object based on decorators or validation schema.
* Common method for `validateOrReject` and `validate` methods.
*/
Validator.prototype.coreValidate = function (objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions) {
var object = typeof objectOrSchemaName === "string" ? objectOrValidationOptions : objectOrSchemaName;
var options = typeof objectOrSchemaName === "string" ? maybeValidatorOptions : objectOrValidationOptions;
var schema = typeof objectOrSchemaName === "string" ? objectOrSchemaName : undefined;
var executor = new ValidationExecutor(this, options);
var validationErrors = [];
executor.execute(object, schema, validationErrors);
return Promise.all(executor.awaitingPromises).then(function () {
return executor.stripEmptyErrors(validationErrors);
});
};
/**
* Performs validation of the given object based on decorators or validation schema.
*/
Validator.prototype.validate = function (objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions) {
return this.coreValidate(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions);
};
/**
* Performs validation of the given object based on decorators or validation schema and reject on error.
*/
Validator.prototype.validateOrReject = function (objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var errors;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.coreValidate(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions)];
case 1:
errors = _a.sent();
if (errors.length)
return [2 /*return*/, Promise.reject(errors)];
return [2 /*return*/];
}
});
});
};
/**
* Performs validation of the given object based on decorators or validation schema.
*/
Validator.prototype.validateSync = function (objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions) {
var object = typeof objectOrSchemaName === "string" ? objectOrValidationOptions : objectOrSchemaName;
var options = typeof objectOrSchemaName === "string" ? maybeValidatorOptions : objectOrValidationOptions;
var schema = typeof objectOrSchemaName === "string" ? objectOrSchemaName : undefined;
var executor = new ValidationExecutor(this, options);
executor.ignoreAsyncValidations = true;
var validationErrors = [];
executor.execute(object, schema, validationErrors);
return executor.stripEmptyErrors(validationErrors);
};
return Validator;
}());
export { Validator };
//# sourceMappingURL=Validator.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
//# sourceMappingURL=ValidatorConstraintInterface.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/validation/ValidatorConstraintInterface.ts"],"names":[],"mappings":"","file":"ValidatorConstraintInterface.js","sourcesContent":["import {ValidationArguments} from \"./ValidationArguments\";\n/**\n * Custom validators must implement this interface to provide custom validation logic.\n */\nexport interface ValidatorConstraintInterface {\n\n /**\n * Method to be called to perform custom validation over given value.\n */\n validate(value: any, validationArguments?: ValidationArguments): Promise<boolean>|boolean;\n\n /**\n * Gets default message when validation for this constraint fail.\n */\n defaultMessage?(validationArguments?: ValidationArguments): string;\n\n}"],"sourceRoot":".."}

View File

@@ -0,0 +1,3 @@
//# sourceMappingURL=ValidatorOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/validation/ValidatorOptions.ts"],"names":[],"mappings":"","file":"ValidatorOptions.js","sourcesContent":["/**\n * Options passed to validator during validation.\n */\nexport interface ValidatorOptions {\n /**\n * If set to true then validator will skip validation of all properties that are undefined in the validating object.\n */\n skipUndefinedProperties?: boolean;\n\n /**\n * If set to true then validator will skip validation of all properties that are null in the validating object.\n */\n skipNullProperties?: boolean;\n\n /**\n * If set to true then validator will skip validation of all properties that are null or undefined in the validating object.\n */\n skipMissingProperties?: boolean;\n\n /**\n * If set to true validator will strip validated object of any properties that do not have any decorators.\n *\n * Tip: if no other decorator is suitable for your property use @Allow decorator.\n */\n whitelist?: boolean;\n\n /**\n * If set to true, instead of stripping non-whitelisted properties validator will throw an error\n */\n forbidNonWhitelisted?: boolean;\n\n /**\n * Groups to be used during validation of the object.\n */\n groups?: string[];\n\n /**\n * If set to true, the validation will not use default messages.\n * Error message always will be undefined if its not explicitly set.\n */\n dismissDefaultMessages?: boolean;\n\n /**\n * ValidationError special options.\n */\n validationError?: {\n\n /**\n * Indicates if target should be exposed in ValidationError.\n */\n target?: boolean;\n\n /**\n * Indicates if validated value should be exposed in ValidationError.\n */\n value?: boolean;\n\n };\n\n /**\n * Settings true will cause fail validation of unknown objects.\n */\n forbidUnknownValues?: boolean;\n\n}\n"],"sourceRoot":".."}