Files
ipal-kit/dist/modules/forms/validateSubmission.js
T
2026-07-31 23:21:51 +02:00

79 lines
2.7 KiB
JavaScript

/** Field block types that don't carry a submittable value. */ const NON_DATA_BLOCKS = new Set([
'message'
]);
/** Hard ceiling on a single field's length, independent of the form config. */ const MAX_FIELD_LENGTH = 5000;
/**
* Checks submitted data against the form's own definition, rather than trusting
* whatever arrived.
*
* The server action is a public endpoint: a caller can skip the rendered form
* and post arbitrary keys. Without this, unknown fields would be stored,
* required fields could be missing, and an oversized value could sail through.
* So we load the form, keep only keys that are real fields, reject when a
* required one is blank, and cap length.
*
* Returns the loaded form on success so the caller doesn't fetch it twice, and
* a code + offending field on failure so the frontend can point at it.
*/ export async function validateSubmission(payload, formId, data) {
let form;
try {
form = await payload.findByID({
id: formId,
collection: 'forms',
depth: 0
});
} catch {
return {
ok: false,
reason: 'not_found'
};
}
const fields = (form.fields ?? []).filter((f)=>typeof f.name === 'string' && !NON_DATA_BLOCKS.has(f.blockType ?? ''));
const known = new Map(fields.map((f)=>[
f.name,
f
]));
const cleaned = {};
for (const field of fields){
const value = data[field.name];
const isBlank = value == null || typeof value === 'string' && value.trim() === '' || value === false;
if (field.required && isBlank) {
return {
field: field.name,
kind: 'required',
ok: false,
reason: 'invalid'
};
}
if (typeof value === 'string' && value.length > MAX_FIELD_LENGTH) {
return {
field: field.name,
kind: 'too_long',
ok: false,
reason: 'invalid'
};
}
// Only carry through keys that belong to the form — unknown keys from a
// hand-crafted request are dropped, not stored.
if (value !== undefined) {
cleaned[field.name] = value;
}
}
// Reject outright if the payload carried keys the form doesn't define — a
// sign the request wasn't produced by the rendered form.
const unknownKeys = Object.keys(data).filter((k)=>!known.has(k));
if (unknownKeys.length > 0) {
return {
kind: 'unknown_fields',
ok: false,
reason: 'invalid'
};
}
return {
cleaned,
form,
ok: true
};
}
//# sourceMappingURL=validateSubmission.js.map