alm
Version:
The best IDE for TypeScript
69 lines (68 loc) • 3.31 kB
JavaScript
;
/// Not useful for user input validation
// But great for simple config validation
// works only by "n" valid options
Object.defineProperty(exports, "__esModule", { value: true });
exports.types = {
string: 'string',
boolean: 'boolean',
number: 'number',
object: 'object',
array: 'array',
};
var SimpleValidator = /** @class */ (function () {
function SimpleValidator(validationInfo) {
var _this = this;
this.validationInfo = validationInfo;
this.validate = function (toValidate) {
var errors = { invalidValues: [], extraKeys: [], errorMessage: '' };
Object.keys(toValidate).forEach(function (k) {
// Check extra keys
if (!_this.validationInfo[k]) {
if (_this.potentialLowerCaseMatch[k]) {
errors.extraKeys.push("Key: '" + k + "' is a potential lower case match for '" + _this.potentialLowerCaseMatch[k] + "'. Fix the casing.");
}
else {
errors.extraKeys.push("Unknown Option: " + k);
}
}
else {
var validationInfo = _this.validationInfo[k];
var value_1 = toValidate[k];
/** Do an array check */
if (validationInfo.type === 'array') {
if (!Array.isArray(value_1)) {
errors.invalidValues.push("Key: '" + k + "' should be an array. But set value is " + value_1);
}
/** TODO: check sub members */
}
else if (validationInfo.type === 'object') {
if (typeof value_1 !== 'object') {
errors.invalidValues.push("Key: '" + k + "' should be an object. But set value is " + value_1);
}
/** TODO: check sub members */
}
else if (typeof value_1 !== validationInfo.type) {
errors.invalidValues.push("Key: '" + k + "' has a value '" + JSON.stringify(value_1) + "' of an invalid type: " + typeof value_1);
}
/** Do a valid values check */
if (typeof value_1 === 'string' && validationInfo.validStringValues && validationInfo.validStringValues.length) {
var validValues = validationInfo.validStringValues;
if (!validValues.some(function (valid) { return valid.toLowerCase() === value_1.toLowerCase(); })) {
errors.invalidValues.push("Key: '" + k + "' has an invalid value: " + value_1);
}
}
}
});
var total = errors.invalidValues.concat(errors.extraKeys);
if (total.length) {
errors.errorMessage = total.join("\n");
}
return errors;
};
this.potentialLowerCaseMatch = {};
Object.keys(validationInfo).forEach(function (k) { return _this.potentialLowerCaseMatch[k.toLowerCase()] = k; });
}
return SimpleValidator;
}());
exports.SimpleValidator = SimpleValidator;