46 lines
2.5 KiB
JavaScript
46 lines
2.5 KiB
JavaScript
/** Preserve protocol types; false and zero are valid answers, not missing input. */
|
|
export function formFieldVisible(field, answers) {
|
|
return field?.hidden !== true && (field?.when ?? []).every((condition) =>
|
|
condition.op === 'neq' ? answers[condition.key] !== condition.value : answers[condition.key] === condition.value);
|
|
}
|
|
|
|
export function formFieldValue(field, raw) {
|
|
if (raw === '') return undefined;
|
|
if (field.type === 'boolean') return raw === 'true';
|
|
if (field.type === 'number' || field.type === 'integer') return Number(raw);
|
|
return raw;
|
|
}
|
|
|
|
export function formAnswerError(fields, answers) {
|
|
for (const field of fields ?? []) {
|
|
if (!formFieldVisible(field, answers) || field.type === 'external') continue;
|
|
const value = answers[field.key];
|
|
const missing = value == null || value === '' || (Array.isArray(value) && !value.length);
|
|
const label = field.title || field.key;
|
|
if (missing) { if (field.required) return `Answer ${label} before sending.`; continue; }
|
|
if (['number', 'integer'].includes(field.type)) {
|
|
if (typeof value !== 'number' || !Number.isFinite(value) || (field.type === 'integer' && !Number.isInteger(value))) return `${label} needs a valid ${field.type}.`;
|
|
if (typeof field.minimum === 'number' && value < field.minimum) return `${label} must be at least ${field.minimum}.`;
|
|
if (typeof field.maximum === 'number' && value > field.maximum) return `${label} must be at most ${field.maximum}.`;
|
|
}
|
|
if (field.type === 'boolean' && typeof value !== 'boolean') return `${label} needs Yes or No.`;
|
|
if (typeof value === 'string') {
|
|
if (field.min_length != null && value.length < field.min_length) return `${label} is too short.`;
|
|
if (field.max_length != null && value.length > field.max_length) return `${label} is too long.`;
|
|
}
|
|
if (Array.isArray(value)) {
|
|
if (field.min_items != null && value.length < field.min_items) return `Select at least ${field.min_items} choices for ${label}.`;
|
|
if (field.max_items != null && value.length > field.max_items) return `Select at most ${field.max_items} choices for ${label}.`;
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
export function visibleFormAnswers(fields, answers) {
|
|
return Object.fromEntries((fields ?? []).filter(f => formFieldVisible(f,answers) && f.type !== 'external' && answers[f.key] !== undefined).map(f => [f.key, answers[f.key]]));
|
|
}
|
|
|
|
export function safeFormURL(raw) {
|
|
try { const url=new URL(raw); return ['http:','https:'].includes(url.protocol) ? url.href : null; } catch { return null; }
|
|
}
|