forked from validatem/core
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.0 KiB
JavaScript
34 lines
1.0 KiB
JavaScript
"use strict";
|
|
|
|
const defaultValue = require("default-value");
|
|
|
|
const normalizeRules = require("@validatem/normalize-rules");
|
|
const matchValidationError = require("@validatem/match-validation-error");
|
|
const validationResult = require("@validatem/validation-result");
|
|
|
|
const composeRules = require("./compose-rules");
|
|
|
|
module.exports = function applyValidators(value, rules, context = {}) {
|
|
let normalizedRules = normalizeRules(rules, { normalizeObjects: true });
|
|
let validator = composeRules.compose(normalizedRules);
|
|
|
|
// FIXME: Document this option!
|
|
let finalContext = (process.env.VALIDATEM_NO_HEURISTICS === "1")
|
|
? { ...context, __validatemNoHeuristics: true }
|
|
: context;
|
|
|
|
let { errors, newValue } = validator(value, finalContext);
|
|
|
|
// NOTE: We mutate the error here, because Error objects are not safely cloneable
|
|
for (let error of errors) {
|
|
if (matchValidationError(error) && error.value == null) {
|
|
error.value = value;
|
|
}
|
|
}
|
|
|
|
return validationResult({
|
|
errors: errors,
|
|
newValue: defaultValue(newValue, value)
|
|
});
|
|
};
|