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.
29 lines
875 B
JavaScript
29 lines
875 B
JavaScript
4 years ago
|
"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);
|
||
|
|
||
|
let { errors, newValue } = validator(value, context);
|
||
|
|
||
|
// 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)
|
||
|
});
|
||
|
};
|