import _ from "lodash" /** Converts a range bound to a number, or null if there is no bound. * Older designs store bounds as strings (e.g. "10"). An empty string means no bound. * Uses the same numeric conversion as a < or > comparison, so "1,5" or "15-20" gives NaN, which never fails a check. */ export function toRangeBound(bound: unknown): number | null { if (bound == null) { return null } if (typeof bound === "string" && bound.trim() === "") { return null } return Number(bound) } // Compiles validations export default class ValidationCompiler { locale?: string constructor(locale?: string) { this.locale = locale } compileString = (str: any) => { // If no base or null, return null if (str == null || !str._base) { return null } // Return for locale if present if (str[this.locale || "en"]) { return str[this.locale || "en"] } // Return base if present return str[str._base] || "" } compileValidationMessage = (val: any) => { const str = this.compileString(val.message) if (str) { return str } return true } compileValidation = (val: any) => { switch (val.op) { case "lengthRange": return (answer: any) => { const value = answer != null && answer.value != null ? answer.value : "" const len = value.length const min = toRangeBound(val.rhs.literal.min) const max = toRangeBound(val.rhs.literal.max) if (min != null && len < min) { return this.compileValidationMessage(val) } if (max != null && len > max) { return this.compileValidationMessage(val) } return null } case "regex": return (answer: any) => { const value = answer != null && answer.value != null ? answer.value : "" if (value.match(val.rhs.literal)) { return null } return this.compileValidationMessage(val) } case "range": return (answer: any) => { let value = answer != null ? answer.value : null if (value === null || value === undefined) { return null } // For units question, get quantity if (value.quantity != null) { value = value.quantity } const min = toRangeBound(val.rhs.literal.min) const max = toRangeBound(val.rhs.literal.max) if (min != null && value < min) { return this.compileValidationMessage(val) } if (max != null && value > max) { return this.compileValidationMessage(val) } return null } default: throw new Error("Unknown validation op " + val.op) } } compileValidations = (vals: any) => { const compVals = _.map(vals, this.compileValidation) return (answer: any) => { for (let compVal of compVals) { const result = compVal(answer) if (result) { return result } } return null } } }