fluent-ts-validator
Version:
A fluent validator written in TypeScript
81 lines • 3.09 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const shared_1 = require("../shared");
const RuleApplicationOutcome_1 = require("./RuleApplicationOutcome");
const successfulOutcome = new RuleApplicationOutcome_1.RuleApplicationOutcome();
class ValidationRule {
constructor(lambdaExpression) {
this.lambdaExpression = lambdaExpression;
this.validators = [];
this.conditions = [];
// the best way I could think of to get hold of the propertyName was via regex
// (the identified propertyName will be used later to specify where a validation failure came from)
// obviously, something like a native nameof-function in TypeScript would be way nicer
// unfortunately, it does not exist yet
let regexArray = lambdaExpression.toString().match("\\s+\\w+\\.(\\w+(\\.\\w+)*)");
this.propertyName = regexArray && regexArray.length > 1 ? regexArray[1] : lambdaExpression.toString();
this.errorMessage = `${this.propertyName} is invalid`;
}
setPropertyName(propertyName) {
this.propertyName = propertyName;
}
addValidator(validator) {
this.validators.push(validator);
}
setErrorCode(errorCode) {
this.errorCode = errorCode;
}
setErrorMessage(errorMessage) {
this.errorMessage = errorMessage;
}
setSeverity(severity) {
this.severity = severity;
}
addCondition(condition) {
if (condition) {
this.conditions.push(condition);
}
}
onFailure(callback) {
this.callback = callback;
}
apply(input) {
const propertyValue = this.lambdaExpressionResultWith(input);
if (this.isValid(input, propertyValue)) {
return successfulOutcome;
}
const failure = this.createValidationFailure(input, propertyValue);
this.invokeCallbackWith(failure);
return new RuleApplicationOutcome_1.RuleApplicationOutcome(failure);
}
lambdaExpressionResultWith(input) {
try {
return this.lambdaExpression(input);
}
catch (e) {
return undefined;
}
}
isValid(input, propertyValue) {
return this.isNoValidationRequired(input) || this.allValidatorsAreValid(propertyValue);
}
isNoValidationRequired(input) {
return !this.isValidationRequired(input);
}
isValidationRequired(input) {
return this.conditions.length === 0 || this.conditions.every(cond => cond.shouldDoValidation(input));
}
allValidatorsAreValid(propertyValue) {
return this.validators.every(validator => validator.isValid(propertyValue));
}
createValidationFailure(input, propertyValue) {
return new shared_1.ValidationFailure(input, this.propertyName, propertyValue, this.errorCode, this.errorMessage, this.severity);
}
invokeCallbackWith(failure) {
if (this.callback) {
this.callback(failure);
}
}
}
exports.ValidationRule = ValidationRule;
//# sourceMappingURL=ValidationRule.js.map