@dwp/govuk-casa
Version:
A framework for building GOVUK Collect-And-Submit-Applications
65 lines • 2.31 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ValidatorFactory_js_1 = __importDefault(require("../ValidatorFactory.js"));
const ValidationError_js_1 = __importDefault(require("../ValidationError.js"));
const utils_js_1 = require("../utils.js");
/**
* @typedef {import("../../casa").ErrorMessageConfig} ErrorMessageConfig
* @access private
*/
/**
* @typedef {object} WordcountConfigOptions
* @property {ErrorMessageConfig} errorMsgMax Error message to use on max length
* failure
* @property {ErrorMessageConfig} errorMsgMin Error message to use on min length
* failure
* @property {number} max Maximum string length allowed
* @property {number} min Minimum string length required
*/
/**
* Test the number of words in a string.
*
* See {@link WordcountConfigOptions} for `make()` options.
*
* @memberof Validators
* @augments ValidatorFactory
*/
class WordCount extends ValidatorFactory_js_1.default {
name = "wordCount";
count(input) {
return (input.match(/\S+/g) || []).length;
}
validate(inputValue = "", dataContext = {}) {
const { errorMsgMax = {
inline: "validation:rule.wordCount.max.inline",
summary: "validation:rule.wordCount.max.summary",
}, errorMsgMin = {
inline: "validation:rule.wordCount.min.inline",
summary: "validation:rule.wordCount.min.summary",
}, min, max, } = this.config;
let errorMsg;
let valid = true;
if (typeof max !== "undefined" &&
(inputValue.match(/\S+/g) || []).length > max) {
valid = false;
errorMsg = errorMsgMax;
}
if (typeof min !== "undefined" &&
(inputValue.match(/\S+/g) || []).length < min) {
valid = false;
errorMsg = errorMsgMin;
}
return valid ? [] : [ValidationError_js_1.default.make({ errorMsg, dataContext })];
}
sanitise(value) {
if (value !== undefined) {
return (0, utils_js_1.stringifyInput)(value);
}
return undefined;
}
}
exports.default = WordCount;
//# sourceMappingURL=wordCount.js.map