@dwp/govuk-casa
Version:
A framework for building GOVUK Collect-And-Submit-Applications
64 lines • 2.34 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = __importDefault(require("lodash"));
const utils_js_1 = require("../utils.js");
const ValidatorFactory_js_1 = __importDefault(require("../ValidatorFactory.js"));
const ValidationError_js_1 = __importDefault(require("../ValidationError.js"));
const { isPlainObject } = lodash_1.default; // CommonJS
/**
* @typedef {import("../../casa").ErrorMessageConfig} ErrorMessageConfig
* @access private
*/
/**
* @typedef {object} RequiredConfigOptions
* @property {ErrorMessageConfig} errorMsg Error message config
*/
/**
* Test if value is present.
*
* Value is required. The following values will fail this rule: (all values that
* satisfy `isEmpty()`) plus '\s'
*
* See {@link RequiredConfigOptions} for `make()` options.
*
* @memberof Validators
* @augments ValidatorFactory
*/
class Required extends ValidatorFactory_js_1.default {
name = "required";
validate(value, dataContext = {}) {
const { errorMsg = {
inline: "validation:rule.required.inline",
summary: "validation:rule.required.summary",
}, } = this.config;
if (!(0, utils_js_1.isEmpty)(value)) {
return [];
}
return [ValidationError_js_1.default.make({ errorMsg, dataContext })];
}
sanitise(value) {
const coerce = (val) => {
const s = (0, utils_js_1.stringifyInput)(val, undefined);
return s === undefined ? undefined : s.replace(/^\s+$/, "");
};
if ((0, utils_js_1.isStringable)(value)) {
return coerce(value);
}
// Coerce all elements to Strings.
// This only supports one dimensional array, with stringable element.
if (Array.isArray(value)) {
return value.map(coerce);
}
// Coerce all elements to Strings.
// This only supports a one dimensional object, with stringable elements.
if (isPlainObject(value)) {
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, coerce(v)]));
}
return undefined;
}
}
exports.default = Required;
//# sourceMappingURL=required.js.map