|
| 1 | +/*! |
| 2 | + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors |
| 3 | + * SPDX-License-Identifier: AGPL-3.0-or-later |
| 4 | + */ |
| 5 | +import { InvalidFilenameError, InvalidFilenameErrorReason, validateFilename } from '@nextcloud/files' |
| 6 | +import { t } from '@nextcloud/l10n' |
| 7 | + |
| 8 | +/** |
| 9 | + * Get the validity of a filename (empty if valid). |
| 10 | + * This can be used for `setCustomValidity` on input elements |
| 11 | + * @param name The filename |
| 12 | + * @param escape Escape the matched string in the error (only set when used in HTML) |
| 13 | + */ |
| 14 | +export function getGuestNameValidity(name: string, escape = false): string { |
| 15 | + if (name.trim() === '') { |
| 16 | + return t('files', 'Filename must not be empty.') |
| 17 | + } |
| 18 | + |
| 19 | + if (name.startsWith('.')) { |
| 20 | + return t('files', 'Names must not start with a dot.') |
| 21 | + } |
| 22 | + |
| 23 | + try { |
| 24 | + validateFilename(name) |
| 25 | + return '' |
| 26 | + } catch (error) { |
| 27 | + if (!(error instanceof InvalidFilenameError)) { |
| 28 | + throw error |
| 29 | + } |
| 30 | + |
| 31 | + switch (error.reason) { |
| 32 | + case InvalidFilenameErrorReason.Character: |
| 33 | + return t('files', '"{char}" is not allowed inside a name.', { char: error.segment }, undefined, { escape }) |
| 34 | + case InvalidFilenameErrorReason.ReservedName: |
| 35 | + return t('files', '"{segment}" is a reserved name and not allowed.', { segment: error.segment }, undefined, { escape: false }) |
| 36 | + case InvalidFilenameErrorReason.Extension: |
| 37 | + if (error.segment.match(/\.[a-z]/i)) { |
| 38 | + return t('files', '"{extension}" is not an allowed name.', { extension: error.segment }, undefined, { escape: false }) |
| 39 | + } |
| 40 | + return t('files', 'Names must not end with "{extension}".', { extension: error.segment }, undefined, { escape: false }) |
| 41 | + default: |
| 42 | + return t('files', 'Invalid name.') |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments