Form files: the visitor is told when the problem is the file — why and what to do; UTF-8 file names
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
b6f9f34705
commit
97202ee03e
@@ -145,26 +145,29 @@ export type FileRefusal =
|
||||
|
||||
/**
|
||||
* Name check, before any byte of the file: the last extension must belong to
|
||||
* one of the allowed types, and NO extension of the name may be a risky one
|
||||
* ("cv.pdf.exe", "cv.exe.pdf") unless the project allowed it.
|
||||
* one of the allowed types (else `type`: simply another format), and NO
|
||||
* extension of the name may be a risky one ("cv.pdf.exe", "cv.exe.pdf") unless
|
||||
* the project allowed it, nor a second known one ("cv.pdf.docx") — else `refused`.
|
||||
*/
|
||||
export function matchFileType(
|
||||
name: string,
|
||||
allowed: readonly string[],
|
||||
types: Record<string, FormFileType>,
|
||||
risky: ReadonlySet<string>,
|
||||
): { key: string; type: FormFileType } | { refused: 'name' } {
|
||||
): { key: string; type: FormFileType } | { refused: 'refused' | 'type' } {
|
||||
const extensions = fileExtensions(name.split(/[/\\]/).pop() ?? '')
|
||||
const last = extensions.at(-1)
|
||||
if (!last || extensions.some((e) => risky.has(e))) {return { refused: 'name' }}
|
||||
// A program, an archive, a macro-enabled file — refused as such, not as "another format".
|
||||
if (extensions.some((e) => risky.has(e))) {return { refused: 'refused' }}
|
||||
if (!last) {return { refused: 'type' }}
|
||||
// "cv.pdf.docx": an extra extension that names another known type hides what the file is.
|
||||
const known = new Set(Object.values(types).flatMap((t) => t.extensions))
|
||||
if (extensions.slice(0, -1).some((e) => known.has(e))) {return { refused: 'name' }}
|
||||
if (extensions.slice(0, -1).some((e) => known.has(e))) {return { refused: 'refused' }}
|
||||
for (const key of allowed) {
|
||||
const type = types[key]
|
||||
if (type?.extensions.includes(last)) {return { type, key }}
|
||||
}
|
||||
return { refused: 'name' }
|
||||
return { refused: 'type' }
|
||||
}
|
||||
|
||||
/** Whole-file check, once the file is in memory. Returns the refusal, or null when it passes. */
|
||||
|
||||
@@ -22,10 +22,19 @@ export type FormFileFailure = {
|
||||
field: string
|
||||
/** The file's name as the visitor knows it (cleaned of control characters). */
|
||||
file?: string
|
||||
kind: 'file_count' | 'file_too_large' | 'file_type' | 'required' | 'unknown_fields'
|
||||
/**
|
||||
* - `file_too_large` — over the limit (`max`, MB)
|
||||
* - `file_type` — a format the field does not accept (`types`)
|
||||
* - `file_refused` — the right extension but not acceptable: the content does not match it, macros, a
|
||||
* program, an archive, a doubled extension, or the project's scanner said no
|
||||
* - `file_count` — more files than the field takes (`max`)
|
||||
*/
|
||||
kind: 'file_count' | 'file_refused' | 'file_too_large' | 'file_type' | 'required' | 'unknown_fields'
|
||||
/** The limit: MB for file_too_large, a count for file_count. */
|
||||
max?: number
|
||||
/** "PDF, DOC, DOCX" — for file_type. */
|
||||
/** True when the field is not required — the visitor may send the form without the file. */
|
||||
optional?: boolean
|
||||
/** "PDF, DOC, DOCX" — the formats the field accepts. */
|
||||
types?: string
|
||||
}
|
||||
|
||||
@@ -79,34 +88,35 @@ export function createFileGate({
|
||||
const file = displayName(rawName)
|
||||
const count = (counts.get(fieldName) ?? 0) + 1
|
||||
counts.set(fieldName, count)
|
||||
if (count > limits.maxFiles) {return { failure: { field: fieldName, kind: 'file_count', max: limits.maxFiles } }}
|
||||
const optional = !field.required
|
||||
if (count > limits.maxFiles) {return { failure: { field: fieldName, kind: 'file_count', max: limits.maxFiles, optional } }}
|
||||
|
||||
const types = describeFileTypes(limits.allowedTypes, options.types).labels
|
||||
const typeFailure: FormFileFailure = { field: fieldName, file, kind: 'file_type', types }
|
||||
const refusedFailure: FormFileFailure = { field: fieldName, file, kind: 'file_refused', optional, types }
|
||||
const match = matchFileType(rawName, limits.allowedTypes, options.types, options.risky)
|
||||
if ('refused' in match) {return { failure: typeFailure }}
|
||||
if ('refused' in match) {return { failure: match.refused === 'type' ? { ...refusedFailure, kind: 'file_type' } : refusedFailure }}
|
||||
|
||||
const maxBytes = Math.max(0, Math.min(limits.maxBytes, limits.maxTotalBytes - total))
|
||||
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(limits.maxBytes) })
|
||||
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(limits.maxBytes), optional })
|
||||
let checked = false
|
||||
return {
|
||||
slot: {
|
||||
checkStart: (head) => {
|
||||
if (checked || head.length < Math.min(SIGNATURE_BYTES, 4)) {return null}
|
||||
checked = true
|
||||
return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? typeFailure : null
|
||||
return looksExecutable(head) || signatureMatches(match.key, head.subarray(0, SIGNATURE_BYTES)) === false ? refusedFailure : null
|
||||
},
|
||||
maxBytes,
|
||||
tooLarge,
|
||||
},
|
||||
token: { field: fieldName, file, key: match.key, maxBytes, rawName, tooLarge, typeFailure },
|
||||
token: { field: fieldName, file, key: match.key, maxBytes, rawName, refusedFailure, tooLarge },
|
||||
}
|
||||
}
|
||||
|
||||
const finish = async (token: BeginToken, data: Uint8Array): Promise<FormFileFailure | null> => {
|
||||
if (data.length > token.maxBytes) {return token.tooLarge()}
|
||||
const type = options.types[token.key]
|
||||
if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.typeFailure}
|
||||
if ((await checkFileContent(token.key, type, data, { strictPdf: options.strictPdf })) !== null) {return token.refusedFailure}
|
||||
const file: AcceptedFormFile = {
|
||||
name: safeFileName(token.rawName, type.extensions[0]),
|
||||
type: token.key,
|
||||
@@ -118,9 +128,9 @@ export function createFileGate({
|
||||
if (options.scan) {
|
||||
try {
|
||||
const verdict = await options.scan({ name: file.name, type: file.type, data, field: file.field, size: file.size })
|
||||
if (!verdict?.ok) {return token.typeFailure}
|
||||
if (!verdict?.ok) {return token.refusedFailure}
|
||||
} catch {
|
||||
return token.typeFailure
|
||||
return token.refusedFailure
|
||||
}
|
||||
}
|
||||
total += data.length
|
||||
@@ -145,8 +155,8 @@ type BeginToken = {
|
||||
key: string
|
||||
maxBytes: number
|
||||
rawName: string
|
||||
refusedFailure: FormFileFailure
|
||||
tooLarge: () => FormFileFailure
|
||||
typeFailure: FormFileFailure
|
||||
}
|
||||
|
||||
export type FileGate = ReturnType<typeof createFileGate>
|
||||
|
||||
@@ -132,6 +132,8 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
|
||||
|
||||
const source = Readable.fromWeb(req.body as never)
|
||||
const parser = busboy({
|
||||
// browsers send file names as UTF-8 ("Życiorys.pdf"); the parser's default would read them as Latin-1
|
||||
defParamCharset: 'utf8',
|
||||
headers: { 'content-type': contentType },
|
||||
limits: { fields: 8, fieldSize: VALUES_BYTES, files: options.maxFiles * 4 + 1, fileSize: Math.floor(options.maxSizeMB * MB) + 1 },
|
||||
})
|
||||
|
||||
@@ -131,22 +131,25 @@ export function fileFieldRules(field: BuilderField): Required<BuilderFileLimits>
|
||||
export function fileFieldError(
|
||||
field: BuilderField,
|
||||
files: readonly BuilderFile[],
|
||||
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileTooLarge' | 'fileType' | 'validation'>,
|
||||
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileOptional' | 'fileTooLarge' | 'fileType' | 'validation'>,
|
||||
): string | undefined {
|
||||
const rules = fileFieldRules(field)
|
||||
const label = field.label || field.name || ''
|
||||
const generic = texts.validation.replace('{field}', label)
|
||||
if (files.length > rules.maxFiles) {return (texts.fileCount ?? generic).replace('{field}', label).replace('{max}', String(rules.maxFiles))}
|
||||
// On a field that is not required the visitor may also send the form without the file — say so.
|
||||
const say = (text: string | undefined, fill: (text: string) => string) =>
|
||||
text ? `${fill(text)}${!field.required && texts.fileOptional ? ` ${texts.fileOptional}` : ''}` : generic
|
||||
if (files.length > rules.maxFiles) {return say(texts.fileCount, (t) => t.replace('{field}', label).replace('{max}', String(rules.maxFiles)))}
|
||||
for (const file of files) {
|
||||
if (rules.extensions.length > 0 && !rules.extensions.includes(fileExtensions(file.name).at(-1) ?? '')) {
|
||||
return (texts.fileType ?? generic).replace('{file}', file.name).replace('{types}', rules.typeLabels)
|
||||
return say(texts.fileType, (t) => t.replace('{file}', file.name).replace('{types}', rules.typeLabels))
|
||||
}
|
||||
if (file.size > rules.maxSizeMB * MB || file.size === 0) {
|
||||
return (texts.fileTooLarge ?? generic).replace('{file}', file.name).replace('{max}', String(rules.maxSizeMB))
|
||||
return say(texts.fileTooLarge, (t) => t.replace('{file}', file.name).replace('{max}', String(rules.maxSizeMB)))
|
||||
}
|
||||
}
|
||||
if (files.reduce((sum, f) => sum + f.size, 0) > rules.maxTotalMB * MB) {
|
||||
return (texts.fileTooLarge ?? generic).replace('{file}', files.at(-1)?.name ?? '').replace('{max}', String(rules.maxTotalMB))
|
||||
return say(texts.fileTooLarge, (t) => t.replace('{file}', files.at(-1)?.name ?? '').replace('{max}', String(rules.maxTotalMB)))
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
@@ -170,7 +173,7 @@ const isBlank = isBlankValue
|
||||
export function validateBuilderFields(
|
||||
fields: BuilderField[],
|
||||
values: Record<string, unknown>,
|
||||
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileTooLarge' | 'fileType' | 'validation'>,
|
||||
texts: Pick<BuilderFormTexts, 'fileCount' | 'fileOptional' | 'fileTooLarge' | 'fileType' | 'validation'>,
|
||||
): Record<string, string> {
|
||||
const errors: Record<string, string> = {}
|
||||
for (const f of inputFields(fields)) {
|
||||
|
||||
@@ -84,6 +84,7 @@ export type BuilderFormTexts = {
|
||||
error?: string
|
||||
/** File field — see FormNotificationTexts. */
|
||||
fileCount?: string
|
||||
fileOptional?: string
|
||||
fileRemove?: string
|
||||
fileTooLarge?: string
|
||||
fileType?: string
|
||||
|
||||
@@ -86,8 +86,13 @@ export type SubmitFailure =
|
||||
/**
|
||||
* The file could not be handed to the mail server (or the form has no
|
||||
* e-mail that may carry it). The file is gone — the visitor must send it
|
||||
* again. `submissionId`: the stored attempt, marked "Not sent".
|
||||
* again. `submissionId`: the stored attempt, marked "Not sent". `field`
|
||||
* and `file`: the File field and the file name(s), so the message shows
|
||||
* at the field and names the file; `optional`: the field is not required.
|
||||
*/
|
||||
field?: string
|
||||
file?: string
|
||||
optional?: boolean
|
||||
reason: 'delivery'
|
||||
submissionId?: number | string
|
||||
success: false
|
||||
@@ -95,14 +100,16 @@ export type SubmitFailure =
|
||||
| {
|
||||
/** The offending field's name, when one field is at fault. */
|
||||
field?: string
|
||||
/** The refused file's name (file_too_large, file_type). */
|
||||
/** The refused file's name (file_too_large, file_type, file_refused). */
|
||||
file?: string
|
||||
/** What was wrong with it. */
|
||||
kind?: 'file_count' | 'file_too_large' | 'file_type' | 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
|
||||
kind?: 'file_count' | 'file_refused' | 'file_too_large' | 'file_type' | 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
|
||||
/** The offending field's label in the page's language — what the visitor sees. Absent when the field has none. */
|
||||
label?: string
|
||||
/** The limit behind file_too_large (MB) or file_count (files). */
|
||||
max?: number
|
||||
/** A file problem on a field that is not required — the form can be sent without the file. */
|
||||
optional?: boolean
|
||||
reason: 'validation'
|
||||
success: false
|
||||
/** Accepted types, "PDF, DOCX" (file_type). */
|
||||
@@ -206,6 +213,7 @@ export async function fileFailure(payload: BasePayload, formId: string, failure:
|
||||
...(failure.file ? { file: failure.file } : {}),
|
||||
...(label ? { label } : {}),
|
||||
...(failure.max !== undefined ? { max: failure.max } : {}),
|
||||
...(failure.optional ? { optional: true } : {}),
|
||||
...(failure.types ? { types: failure.types } : {}),
|
||||
}
|
||||
}
|
||||
@@ -229,9 +237,17 @@ export async function findSubmitAttempt(payload: BasePayload, attemptKey: string
|
||||
limit: 1,
|
||||
where: { attemptKey: { equals: attemptKey } },
|
||||
} as never)
|
||||
const doc = found.docs[0] as { filesDelivery?: string; id: number | string } | undefined
|
||||
const doc = found.docs[0] as { filesDelivery?: string; id: number | string; submissionFiles?: { field?: string; name?: string }[] } | undefined
|
||||
if (!doc) {return null}
|
||||
return doc.filesDelivery === 'failed' ? { reason: 'delivery', submissionId: doc.id, success: false } : { submissionId: doc.id, success: true }
|
||||
if (doc.filesDelivery !== 'failed') {return { submissionId: doc.id, success: true }}
|
||||
const kept = doc.submissionFiles ?? []
|
||||
return {
|
||||
reason: 'delivery',
|
||||
submissionId: doc.id,
|
||||
success: false,
|
||||
...(kept[0]?.field ? { field: kept[0].field } : {}),
|
||||
...(kept.length ? { file: kept.map((f) => f.name).join(', ') } : {}),
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -260,6 +276,7 @@ export async function storeSubmission({
|
||||
} & Pick<SubmitFormArgs, 'formId' | 'locale' | 'payload'>): Promise<SubmitFormResult> {
|
||||
const attachments = getFormAttachments(payload)
|
||||
const delivery: FormFileDelivery | undefined = files.length ? { files } : undefined
|
||||
const fileNames = files.map((f) => ({ name: f.name, field: f.field }))
|
||||
const text = (value: unknown) =>
|
||||
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
|
||||
value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string)
|
||||
@@ -297,7 +314,17 @@ export async function storeSubmission({
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`)
|
||||
}
|
||||
return result.state === 'sent' ? { submissionId: submission.id, success: true } : { reason: 'delivery', submissionId: submission.id, success: false }
|
||||
if (result.state === 'sent') {return { submissionId: submission.id, success: true }}
|
||||
// The message belongs at the File field and names the file — never the mail server's own words.
|
||||
const fileField = validation.fileFields.find((f) => f.name === fileNames[0]?.field)
|
||||
return {
|
||||
field: fileNames[0]?.field,
|
||||
file: fileNames.map((f) => f.name).join(', '),
|
||||
reason: 'delivery',
|
||||
submissionId: submission.id,
|
||||
success: false,
|
||||
...(fileField && !fileField.required ? { optional: true } : {}),
|
||||
}
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
|
||||
return { reason: 'error', success: false }
|
||||
@@ -345,7 +372,7 @@ export async function submitForm(args: SubmitFormArgs): Promise<SubmitFormResult
|
||||
return storeSubmission({ attemptKey, formId, locale, payload, validation })
|
||||
}
|
||||
|
||||
if (hasFiles && !canCarryFiles(validation.form)) {return { reason: 'delivery', success: false }}
|
||||
if (hasFiles && !canCarryFiles(validation.form)) {return { field: Object.keys(files ?? {})[0], reason: 'delivery', success: false }}
|
||||
const gate = createFileGate({ fields: validation.fileFields, options: attachments, transportMaxBytes: await mailAttachmentLimit(payload) })
|
||||
const refused = await checkBufferedFiles(gate, files ?? {})
|
||||
if (refused) {return fileFailure(payload, formId, refused, locale)}
|
||||
|
||||
@@ -12,11 +12,13 @@ export const NOTIFICATION_FALLBACK: NotificationTexts = {
|
||||
back: 'Back',
|
||||
consent: 'Accept the privacy policy to send the form.',
|
||||
error: 'The form could not be sent. Please try again in a moment.',
|
||||
fileCount: 'Attach at most {max} files in "{field}".',
|
||||
fileNotSent: 'We could not send your file. Try again, or send it by e-mail.',
|
||||
fileCount: 'Too many files in "{field}". Remove some: the limit is {max}.',
|
||||
fileNotSent: 'We could not send the file "{file}". Choose a smaller file or another format and try again.',
|
||||
fileOptional: 'You can also send the form without the file.',
|
||||
fileRefused: 'The file "{file}" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file ({types}).',
|
||||
fileRemove: 'Remove {file}',
|
||||
fileTooLarge: '"{file}" is too large. The limit is {max} MB.',
|
||||
fileType: '"{file}" is not an accepted file type. Accepted: {types}.',
|
||||
fileTooLarge: 'The file "{file}" is too large. Choose a file of up to {max} MB.',
|
||||
fileType: 'The file "{file}" is in a format we do not accept. Choose one of: {types}.',
|
||||
next: 'Next',
|
||||
notFound: 'This form is no longer available.',
|
||||
rateLimited: 'Too many attempts. Please wait a moment and try again.',
|
||||
@@ -34,11 +36,13 @@ export const NOTIFICATION_FALLBACK_PL: NotificationTexts = {
|
||||
back: 'Wstecz',
|
||||
consent: 'Zaakceptuj politykę prywatności, aby wysłać formularz.',
|
||||
error: 'Nie udało się wysłać formularza. Spróbuj ponownie za chwilę.',
|
||||
fileCount: 'W polu „{field}” można dodać najwyżej {max} plików.',
|
||||
fileNotSent: 'Nie udało się wysłać pliku. Spróbuj ponownie lub wyślij go e-mailem.',
|
||||
fileCount: 'Za dużo plików w polu „{field}”. Usuń część: limit to {max}.',
|
||||
fileNotSent: 'Nie udało się wysłać pliku „{file}”. Wybierz mniejszy plik lub inny format i spróbuj ponownie.',
|
||||
fileOptional: 'Możesz też wysłać formularz bez pliku.',
|
||||
fileRefused: 'Plik „{file}” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik ({types}).',
|
||||
fileRemove: 'Usuń {file}',
|
||||
fileTooLarge: 'Plik „{file}” jest za duży. Limit to {max} MB.',
|
||||
fileType: 'Plik „{file}” ma niedozwolony typ. Dozwolone: {types}.',
|
||||
fileTooLarge: 'Plik „{file}” jest za duży. Wybierz plik do {max} MB.',
|
||||
fileType: 'Plik „{file}” ma format, którego nie przyjmujemy. Wybierz jeden z: {types}.',
|
||||
next: 'Dalej',
|
||||
notFound: 'Ten formularz nie jest już dostępny.',
|
||||
rateLimited: 'Zbyt wiele prób. Odczekaj chwilę i spróbuj ponownie.',
|
||||
|
||||
@@ -34,6 +34,8 @@ export async function getNotificationTexts({
|
||||
error: f.error || fb.error,
|
||||
fileCount: f.fileCount || fb.fileCount,
|
||||
fileNotSent: f.fileNotSent || fb.fileNotSent,
|
||||
fileOptional: f.fileOptional || fb.fileOptional,
|
||||
fileRefused: f.fileRefused || fb.fileRefused,
|
||||
fileRemove: f.fileRemove || fb.fileRemove,
|
||||
fileTooLarge: f.fileTooLarge || fb.fileTooLarge,
|
||||
fileType: f.fileType || fb.fileType,
|
||||
|
||||
@@ -5,10 +5,16 @@ import type { FormNotificationTexts } from './types.js'
|
||||
* The texts resolveFormMessage needs. The File-field texts are optional, so an
|
||||
* object written before they existed still fits (the field or general text is used).
|
||||
*/
|
||||
export type FormMessageTexts = { [K in 'fileCount' | 'fileNotSent' | 'fileRemove' | 'fileTooLarge' | 'fileType']?: string } & Omit<
|
||||
FormNotificationTexts,
|
||||
'fileCount' | 'fileNotSent' | 'fileRemove' | 'fileTooLarge' | 'fileType'
|
||||
>
|
||||
type FileTextKey = 'fileCount' | 'fileNotSent' | 'fileOptional' | 'fileRefused' | 'fileRemove' | 'fileTooLarge' | 'fileType'
|
||||
export type FormMessageTexts = { [K in FileTextKey]?: string } & Omit<FormNotificationTexts, FileTextKey>
|
||||
|
||||
/** The texts of the File field problems, by result code. */
|
||||
const FILE_TEXT: Partial<Record<string, FileTextKey>> = {
|
||||
file_count: 'fileCount',
|
||||
file_refused: 'fileRefused',
|
||||
file_too_large: 'fileTooLarge',
|
||||
file_type: 'fileType',
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a submitForm result to the user-facing message, interpolating {field}
|
||||
@@ -27,8 +33,11 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
|
||||
switch (result.reason) {
|
||||
case 'consent':
|
||||
return texts.consent
|
||||
case 'delivery':
|
||||
return texts.fileNotSent ?? texts.error
|
||||
case 'delivery': {
|
||||
// The file could not be e-mailed: say it is the file (at its field), never the mail server's own words.
|
||||
if (!texts.fileNotSent) {return texts.error}
|
||||
return withoutFile(texts.fileNotSent.replace('{file}', result.file ?? ''), result.optional, texts)
|
||||
}
|
||||
case 'not_found':
|
||||
return texts.notFound
|
||||
case 'rate_limited':
|
||||
@@ -38,15 +47,16 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
|
||||
case 'validation': {
|
||||
// {field} → the label the visitor sees; no single field at fault → the generic error.
|
||||
const field = result.label || result.field
|
||||
const fill = (text: string) =>
|
||||
text
|
||||
// A problem with a file says so: which file, why, and what to do next.
|
||||
const fileText = texts[FILE_TEXT[result.kind ?? ''] ?? 'fileRemove']
|
||||
if (FILE_TEXT[result.kind ?? ''] && fileText) {
|
||||
const message = fileText
|
||||
.replace('{file}', result.file ?? '')
|
||||
.replace('{max}', result.max === undefined ? '' : String(result.max))
|
||||
.replace('{types}', result.types ?? '')
|
||||
.replace('{field}', field ?? '')
|
||||
if (result.kind === 'file_too_large' && texts.fileTooLarge) {return fill(texts.fileTooLarge)}
|
||||
if (result.kind === 'file_type' && texts.fileType) {return fill(texts.fileType)}
|
||||
if (result.kind === 'file_count' && texts.fileCount) {return fill(texts.fileCount)}
|
||||
return withoutFile(message, result.optional, texts)
|
||||
}
|
||||
return field ? texts.validation.replace('{field}', field) : texts.error
|
||||
}
|
||||
case 'error':
|
||||
@@ -54,3 +64,8 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
|
||||
return texts.error
|
||||
}
|
||||
}
|
||||
|
||||
/** On a field that is not required, a file message ends with "…send the form without the file". */
|
||||
function withoutFile(message: string, optional: boolean | undefined, texts: FormMessageTexts): string {
|
||||
return optional && texts.fileOptional ? `${message} ${texts.fileOptional}` : message
|
||||
}
|
||||
|
||||
@@ -12,8 +12,15 @@ export type FormNotificationTexts = {
|
||||
error: string
|
||||
/** File field: too many files, with {field} and {max}. */
|
||||
fileCount: string
|
||||
/** File field: the e-mail with the file could not be sent — the visitor has to send it again. */
|
||||
/** File field: the e-mail with the file could not be sent — with {file}; the visitor has to send it again. */
|
||||
fileNotSent: string
|
||||
/** File field: added to a file message when the field is not required ("…send the form without the file"). */
|
||||
fileOptional: string
|
||||
/**
|
||||
* File field: the format is allowed but this file is not — its content does not match, it has macros, it is
|
||||
* a program or an archive. With {file} and {types}.
|
||||
*/
|
||||
fileRefused: string
|
||||
/** File field: the button that removes a selected file, with {file}. */
|
||||
fileRemove: string
|
||||
/** File field: a file over the limit, with {file} and {max} (MB). */
|
||||
|
||||
Reference in New Issue
Block a user