diff --git a/docs/AnswerRules.md b/docs/AnswerRules.md new file mode 100644 index 000000000..b407e645b --- /dev/null +++ b/docs/AnswerRules.md @@ -0,0 +1,74 @@ + + +# Answer rules + +Form owners can restrict what respondents enter in text answers. This page lists the rules and explains what happens when you change them. For the stored settings see [DataStructure](./DataStructure.md#extra-settings). + +## Where to set them + +- **Long answer**: in the question menu, "Require a minimum length" and "Limit the maximum length". +- **Short answer**: in the input type menu (the icon at the end of the answer field). Which rules you can set depends on the input type: + +| Input type | Rules | +| --------------------------- | -------------------------------------------------------------- | +| Text | Minimum and maximum length, "Must contain", "Must not contain" | +| Number | A number rule (see below) and "Whole numbers only" | +| URL | Only `http` and `https` addresses | +| Email address, phone number | A valid address or number | +| Custom regular expression | The answer must match the expression | + +The number rules are: any number, between, not between, greater than, at least, less than, at most, equal to and not equal to. Numbers may have decimals unless "Whole numbers only" is on. "Must contain" and "Must not contain" ignore upper and lower case. + +## What respondents see + +- A hint above the answer field names every rule, for example "Enter between 3 and 12 characters" or "Enter a number greater than 0 · Enter a whole number". +- Text fields with a length limit show a character counter below the field, like "11 / 40". Typing stops at the maximum length. +- An answer breaking a rule shows the first broken rule as an error and cannot be submitted. +- The server checks every rule again when a response is submitted or edited, so the rules also hold for answers sent through the API. + +## How changing rules behaves + +### Changing the input type + +Switching a short answer to another input type removes all rules of the previous one: lengths, the number rule, "Whole numbers only" and the required texts. Set them again for the new input type. + +### Changing the number rule + +When you pick another number rule, the editor keeps your number where it can, so you only adjust what is new: + +| New rule | Number it starts with | +| --------------------------------------------------------- | ------------------------------------------------------- | +| At least, less than, greater than, equal to, not equal to | Your lowest number, or your highest if you only set one | +| At most | Your highest number, or your lowest if you only set one | +| Any number | None, the numbers are removed | + +Switching to **between** or **not between** proposes a range from your number: + +| Current rule | Proposed range | +| ------------------------------ | ---------------------------------------------------- | +| A range, like between 1 and 10 | Stays 1 to 10 | +| At most 50, greater than 50 | 0 to 50 | +| At least 18, less than 18 | 18 to 100, up to the next number with one more digit | +| Equal to 7, not equal to 7 | 0 to 14, zero to double the number | +| Any number | 0 to 100 | + +Zero and negative numbers are mirrored, so the lowest number always stays below the highest: at most −5 proposes −10 to −5, equal to −7 proposes −14 to 0, and equal to 0 proposes 0 to 10. + +"Whole numbers only" stays on when you change the number rule. + +### Rules that mean the same + +If you set the same lowest and highest number under "Between", the editor shows the rule as "Equal to", and under "Not between" as "Not equal to". Both mean the same, so respondents see no difference. + +### Limits that do not fit together + +- A minimum above its maximum is not saved: the editor shows "The minimum must not be greater than the maximum" and keeps the previous value. This applies to lengths and to the lowest and highest number of a range. +- A length can be at most 4096 characters, the longest answer Forms stores. "Limit the maximum length" starts at 4096; "Require a minimum length" starts at 1. +- Clearing "Must contain" or "Must not contain" removes that rule. + +### Existing responses + +Changing a rule does not change or remove responses already submitted. The new rules apply to the next submission, and to a response when it is edited. diff --git a/docs/DataStructure.md b/docs/DataStructure.md index 2aabc65ef..1b669beea 100644 --- a/docs/DataStructure.md +++ b/docs/DataStructure.md @@ -243,7 +243,7 @@ Currently supported Question-Types are: ## Extra Settings -Optional extra settings for some [Question Types](#question-types) +Optional extra settings for some [Question Types](#question-types). How the answer rules (lengths, number rules, required texts) behave for form owners and respondents is described in [Answer rules](./AnswerRules.md). | Extra Setting | Question Type | Type | Values | Description | | ----------------------- | ---------------------------------------------- | ---------------- | ------------------------------------------- | --------------------------------------------------------------------------- | @@ -251,8 +251,16 @@ Optional extra settings for some [Question Types](#question-types) | `shuffleOptions` | `dropdown, multiple, multiple_unique, ranking` | Boolean | `true/false` | The list of options should be shuffled | | `optionsLimitMax` | `multiple` | Integer | - | Maximum number of options that can be selected | | `optionsLimitMin` | `multiple` | Integer | - | Minimum number of options that must be selected | -| `validationType` | `short` | string | `null, 'phone', 'email', 'regex', 'number'` | Custom validation for checking a submission | +| `validationType` | `short` | string | `null, 'phone', 'email', 'url', 'regex', 'number'` | Custom validation for checking a submission; `url` accepts `http` and `https` addresses | | `validationRegex` | `short` | string | regular expression | if `validationType` is 'regex' this defines the regular expression to apply | +| `lengthMin` | `short, long` | Integer | `1` to `4096` | Minimum number of characters of the answer; for `short` only without `validationType` | +| `lengthMax` | `short, long` | Integer | `1` to `4096` | Maximum number of characters of the answer, not below `lengthMin`; for `short` only without `validationType` | +| `numberMin` | `short` | Number | - | Lowest number accepted, only with `validationType` 'number' | +| `numberMax` | `short` | Number | - | Highest number accepted, not below `numberMin`, only with `validationType` 'number' | +| `numberExclude` | `short` | Boolean | `true` | Reject the numbers from `numberMin` to `numberMax` instead of accepting only them (*not between*, or *not equal* if both are the same); with `numberMin` only it accepts numbers less than it, with `numberMax` only numbers greater than it; needs at least one | +| `numberInteger` | `short` | Boolean | `true` | Accept whole numbers only, only with `validationType` 'number' | +| `textContains` | `short` | string | `1` to `4096` characters | Text the answer must contain, ignoring case; only without `validationType` | +| `textNotContains` | `short` | string | `1` to `4096` characters | Text the answer must not contain, ignoring case; only without `validationType` | | `allowedFileTypes` | `file` | Array of strings | `'image', 'x-office/document'` | Allowed file types for file upload | | `allowedFileExtensions` | `file` | Array of strings | `'jpg', 'png'` | Allowed file extensions for file upload | | `maxAllowedFilesCount` | `file` | Integer | - | Maximum number of files that can be uploaded, 0 means no limit | diff --git a/lib/Constants.php b/lib/Constants.php index f56977d8e..dc156db3f 100644 --- a/lib/Constants.php +++ b/lib/Constants.php @@ -187,7 +187,8 @@ class Constants { 'phone', 'email', 'regex', - 'number' + 'number', + 'url', ]; // This are allowed extra settings @@ -204,10 +205,23 @@ class Constants { ]; public const EXTRA_SETTINGS_SHORT = [ + 'lengthMax' => ['integer'], + 'lengthMin' => ['integer'], + 'numberExclude' => ['boolean'], + 'numberInteger' => ['boolean'], + 'numberMax' => ['integer', 'double'], + 'numberMin' => ['integer', 'double'], + 'textContains' => ['string'], + 'textNotContains' => ['string'], 'validationType' => ['string'], 'validationRegex' => ['string'], ]; + public const EXTRA_SETTINGS_LONG = [ + 'lengthMax' => ['integer'], + 'lengthMin' => ['integer'], + ]; + public const EXTRA_SETTINGS_FILE = [ 'allowedFileTypes' => ['array'], 'allowedFileExtensions' => ['array'], diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 0db8b7bd4..ab19f6d3c 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -27,8 +27,14 @@ * dateMax?: string|int, * dateMin?: string|int, * dateRange?: bool, + * lengthMax?: int, + * lengthMin?: int, * maxAllowedFilesCount?: int, * maxFileSize?: int, + * numberExclude?: bool, + * numberInteger?: bool, + * numberMax?: int|float, + * numberMin?: int|float, * optionsHighest?: 2|3|4|5|6|7|8|9|10, * optionsLabelHighest?: string, * optionsLabelLowest?: string, @@ -37,6 +43,8 @@ * optionsLowest?: 0|1, * ratingIcon?: "star"|"heart"|"thumb", * shuffleOptions?: bool, + * textContains?: string, + * textNotContains?: string, * timeMax?: string, * timeMin?: string, * timeRange?: bool, diff --git a/lib/Service/FormsService.php b/lib/Service/FormsService.php index 39c74a8ba..e6574f63f 100644 --- a/lib/Service/FormsService.php +++ b/lib/Service/FormsService.php @@ -905,6 +905,7 @@ public function areExtraSettingsValid(array $extraSettings, string $questionType Constants::ANSWER_TYPE_DROPDOWN => Constants::EXTRA_SETTINGS_DROPDOWN, Constants::ANSWER_TYPE_MULTIPLE, Constants::ANSWER_TYPE_MULTIPLEUNIQUE => Constants::EXTRA_SETTINGS_MULTIPLE, Constants::ANSWER_TYPE_SHORT => Constants::EXTRA_SETTINGS_SHORT, + Constants::ANSWER_TYPE_LONG => Constants::EXTRA_SETTINGS_LONG, Constants::ANSWER_TYPE_FILE => Constants::EXTRA_SETTINGS_FILE, Constants::ANSWER_TYPE_DATE => Constants::EXTRA_SETTINGS_DATE, Constants::ANSWER_TYPE_GRID => Constants::EXTRA_SETTINGS_GRID, @@ -927,6 +928,10 @@ public function areExtraSettingsValid(array $extraSettings, string $questionType } } + if (!$this->areAnswerLimitsValid($extraSettings)) { + return false; + } + // Validate extraSettings for specific question types if ($questionType === Constants::ANSWER_TYPE_DATE) { $format = Constants::ANSWER_PHPDATETIME_FORMAT['date']; @@ -1085,6 +1090,73 @@ public function areExtraSettingsValid(array $extraSettings, string $questionType return true; } + /** + * Whether the length and number limits of a text answer are consistent + * + * A length limit is allowed on plain text answers only, a number range only + * on answers validated as number, like whole numbers only. Excluding the + * range of one bound only accepts numbers below the minimum or above the + * maximum. Lengths are counted in characters from 1 + * up to the stored answer length, and a minimum must not exceed its maximum. + * + * @param array $extraSettings the extra settings of the question + * @return bool true if the limits are valid or not set + */ + private function areAnswerLimitsValid(array $extraSettings): bool { + $validationType = $extraSettings['validationType'] ?? null; + $lengthMin = $extraSettings['lengthMin'] ?? null; + $lengthMax = $extraSettings['lengthMax'] ?? null; + $numberMin = $extraSettings['numberMin'] ?? null; + $numberMax = $extraSettings['numberMax'] ?? null; + $numberExclude = $extraSettings['numberExclude'] ?? null; + $numberInteger = $extraSettings['numberInteger'] ?? null; + + foreach (['textContains', 'textNotContains'] as $key) { + $text = $extraSettings[$key] ?? null; + if ($text !== null && ($validationType !== null || $text === '' || mb_strlen($text) > Constants::MAX_STRING_LENGTHS['answerText'])) { + return false; + } + } + + if ($numberExclude !== null && ($numberExclude !== true || ($numberMin === null && $numberMax === null))) { + return false; + } + + if ($numberInteger !== null && ($numberInteger !== true || $validationType !== 'number')) { + return false; + } + + if ($lengthMin !== null || $lengthMax !== null) { + if ($validationType !== null) { + return false; + } + foreach ([$lengthMin, $lengthMax] as $length) { + if ($length !== null && ($length < 1 || $length > Constants::MAX_STRING_LENGTHS['answerText'])) { + return false; + } + } + if ($lengthMin !== null && $lengthMax !== null && $lengthMin > $lengthMax) { + return false; + } + } + + if ($numberMin !== null || $numberMax !== null) { + if ($validationType !== 'number') { + return false; + } + foreach ([$numberMin, $numberMax] as $number) { + if ($number !== null && !is_finite((float)$number)) { + return false; + } + } + if ($numberMin !== null && $numberMax !== null && $numberMin > $numberMax) { + return false; + } + } + + return true; + } + /** * Get list of forms * diff --git a/lib/Service/SubmissionService.php b/lib/Service/SubmissionService.php index b379b9752..c7ed473c8 100644 --- a/lib/Service/SubmissionService.php +++ b/lib/Service/SubmissionService.php @@ -769,6 +769,11 @@ public function validateSubmission(array $questions, array $answers, string $for throw new \InvalidArgumentException(sprintf('Invalid input for question "%s".', $question['text'])); } + if (in_array($question['type'], [Constants::ANSWER_TYPE_SHORT, Constants::ANSWER_TYPE_LONG], true) + && $answers[$questionId][0] !== '') { + $this->validateAnswerLimits($question, $answers[$questionId][0]); + } + // Handle ranking questions: answers must be a permutation of all option IDs if ($question['type'] === Constants::ANSWER_TYPE_RANKING) { $optionIds = array_map(intval(...), array_column($question['options'] ?? [], 'id')); @@ -897,6 +902,9 @@ private function validateShortQuestion(array $question, string $data): bool { return $this->emailValidator->isValid($data); case 'number': return is_numeric($data); + case 'url': + return filter_var($data, FILTER_VALIDATE_URL) !== false + && in_array(strtolower((string)parse_url($data, PHP_URL_SCHEME)), ['http', 'https'], true); case 'phone': // some special characters are used (depending on the locale) $sanitized = str_replace([' ', '(', ')', '.', '/', '-', 'x'], '', $data); @@ -918,6 +926,51 @@ private function validateShortQuestion(array $question, string $data): bool { } } + /** + * Check a text answer against the length limits, the number rule and the + * required or forbidden text of its question + * + * @param array $question the question + * @param string $answer the answer text + * @throws \InvalidArgumentException if the answer breaks one of the rules + */ + private function validateAnswerLimits(array $question, string $answer): void { + $lengthMin = $question['extraSettings']['lengthMin'] ?? null; + $lengthMax = $question['extraSettings']['lengthMax'] ?? null; + $length = mb_strlen($answer); + if (($lengthMin !== null && $length < $lengthMin) || ($lengthMax !== null && $length > $lengthMax)) { + throw new \InvalidArgumentException(sprintf('The answer for question "%s" must be from %d to %d characters long.', $question['text'], $lengthMin ?? 1, $lengthMax ?? Constants::MAX_STRING_LENGTHS['answerText'])); + } + + $numberMin = $question['extraSettings']['numberMin'] ?? null; + $numberMax = $question['extraSettings']['numberMax'] ?? null; + if (($numberMin !== null || $numberMax !== null) && is_numeric($answer)) { + $inRange = ($numberMin === null || +$answer >= $numberMin) && ($numberMax === null || +$answer <= $numberMax); + $exclude = ($question['extraSettings']['numberExclude'] ?? false) === true; + if ($inRange === $exclude) { + throw new \InvalidArgumentException(match (true) { + $numberMin !== null && $numberMin == $numberMax => sprintf($exclude ? 'The answer for question "%s" must not be %s.' : 'The answer for question "%s" must be %s.', $question['text'], $numberMin), + $exclude && $numberMax === null => sprintf('The answer for question "%s" must be a number less than %s.', $question['text'], $numberMin), + $exclude && $numberMin === null => sprintf('The answer for question "%s" must be a number greater than %s.', $question['text'], $numberMax), + $exclude => sprintf('The answer for question "%s" must be a number outside %s to %s.', $question['text'], $numberMin, $numberMax), + default => sprintf('The answer for question "%s" must be a number from %s to %s.', $question['text'], $numberMin ?? '-∞', $numberMax ?? '∞'), + }); + } + } + if (($question['extraSettings']['numberInteger'] ?? false) === true && is_numeric($answer) && floor(+$answer) != +$answer) { + throw new \InvalidArgumentException(sprintf('The answer for question "%s" must be a whole number.', $question['text'])); + } + + $textContains = $question['extraSettings']['textContains'] ?? null; + if ($textContains !== null && mb_stripos($answer, $textContains) === false) { + throw new \InvalidArgumentException(sprintf('The answer for question "%s" must contain "%s".', $question['text'], $textContains)); + } + $textNotContains = $question['extraSettings']['textNotContains'] ?? null; + if ($textNotContains !== null && mb_stripos($answer, $textNotContains) !== false) { + throw new \InvalidArgumentException(sprintf('The answer for question "%s" must not contain "%s".', $question['text'], $textNotContains)); + } + } + private function validateGridQuestion(array $question, array $answers): void { $rowIds = $this->normalizeOptionIds($question['options'] ?? [], Constants::OPTION_TYPE_ROW); $columnIds = $this->normalizeOptionIds($question['options'] ?? [], Constants::OPTION_TYPE_COLUMN); diff --git a/openapi.json b/openapi.json index 58430d3e1..271584908 100644 --- a/openapi.json +++ b/openapi.json @@ -530,6 +530,14 @@ "dateRange": { "type": "boolean" }, + "lengthMax": { + "type": "integer", + "format": "int64" + }, + "lengthMin": { + "type": "integer", + "format": "int64" + }, "maxAllowedFilesCount": { "type": "integer", "format": "int64" @@ -538,6 +546,36 @@ "type": "integer", "format": "int64" }, + "numberExclude": { + "type": "boolean" + }, + "numberInteger": { + "type": "boolean" + }, + "numberMax": { + "anyOf": [ + { + "type": "integer", + "format": "int64" + }, + { + "type": "number", + "format": "double" + } + ] + }, + "numberMin": { + "anyOf": [ + { + "type": "integer", + "format": "int64" + }, + { + "type": "number", + "format": "double" + } + ] + }, "optionsHighest": { "type": "integer", "format": "int64", @@ -586,6 +624,12 @@ "shuffleOptions": { "type": "boolean" }, + "textContains": { + "type": "string" + }, + "textNotContains": { + "type": "string" + }, "timeMax": { "type": "string" }, diff --git a/playwright/e2e/answer-limits.spec.ts b/playwright/e2e/answer-limits.spec.ts new file mode 100644 index 000000000..f5394587c --- /dev/null +++ b/playwright/e2e/answer-limits.spec.ts @@ -0,0 +1,632 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { APIRequestContext, Page } from '@playwright/test' + +import { expect, mergeTests } from '@playwright/test' +import { test as formTest } from '../support/fixtures/form.ts' +import { test as appNavigationTest } from '../support/fixtures/navigation.ts' +import { test as randomUserTest } from '../support/fixtures/random-user.ts' +import { api, waitForApiResponse } from '../support/helpers.ts' +import { QuestionType } from '../support/sections/QuestionType.ts' + +const test = mergeTests(randomUserTest, appNavigationTest, formTest) + +const OCS_HEADERS = { 'OCS-APIRequest': 'true', Accept: 'application/json' } + +/** + * The questions of the limited form: title, type, extra settings, the hint + * respondents see, an answer breaking the rule with its error, and a valid answer + */ +const QUESTIONS = [ + { + key: 'nickname', + type: 'short', + text: 'Nickname', + extraSettings: { lengthMin: 3, lengthMax: 12 }, + hint: 'Enter between 3 and 12 characters', + invalid: 'ab', + error: 'Enter between 3 and 12 characters', + valid: 'abc', + }, + { + key: 'rating', + type: 'short', + text: 'Rating', + extraSettings: { validationType: 'number', numberMin: 1, numberMax: 10 }, + hint: 'Enter a number from 1 to 10', + invalid: '11', + error: 'Enter a number from 1 to 10', + valid: '7', + }, + { + key: 'adults', + type: 'short', + text: 'Age', + extraSettings: { validationType: 'number', numberMin: 18 }, + hint: 'Enter a number of at least 18', + invalid: '17', + error: 'Enter a number of at least 18', + valid: '18', + }, + { + key: 'discount', + type: 'short', + text: 'Discount in percent', + extraSettings: { validationType: 'number', numberMax: 50 }, + hint: 'Enter a number of at most 50', + invalid: '50.5', + error: 'Enter a number of at most 50', + valid: '50', + }, + { + key: 'outside', + type: 'short', + text: 'Outside the usual range', + extraSettings: { + validationType: 'number', + numberMin: 1, + numberMax: 10, + numberExclude: true, + }, + hint: 'Enter a number below 1 or above 10', + invalid: '5', + error: 'Enter a number below 1 or above 10', + valid: '11', + }, + { + key: 'lucky', + type: 'short', + text: 'Lucky number', + extraSettings: { validationType: 'number', numberMin: 7, numberMax: 7 }, + hint: 'Enter the number 7', + invalid: '6', + error: 'Enter the number 7', + valid: '7', + }, + { + key: 'unlucky', + type: 'short', + text: 'Any number but 13', + extraSettings: { + validationType: 'number', + numberMin: 13, + numberMax: 13, + numberExclude: true, + }, + hint: 'Enter any number except 13', + invalid: '13', + error: 'Enter any number except 13', + valid: '12', + }, + { + key: 'price', + type: 'short', + text: 'Price', + extraSettings: { + validationType: 'number', + numberMax: 0, + numberExclude: true, + }, + hint: 'Enter a number greater than 0', + invalid: '0', + error: 'Enter a number greater than 0', + valid: '9.99', + }, + { + key: 'temperature', + type: 'short', + text: 'Temperature', + extraSettings: { + validationType: 'number', + numberMin: 100, + numberExclude: true, + }, + hint: 'Enter a number less than 100', + invalid: '100', + error: 'Enter a number less than 100', + valid: '99.5', + }, + { + key: 'guests', + type: 'short', + text: 'Guests', + extraSettings: { + validationType: 'number', + numberMin: 0, + numberMax: 10, + numberInteger: true, + }, + hint: 'Enter a number from 0 to 10 · Enter a whole number', + invalid: '2.5', + error: 'Enter a whole number', + valid: '2', + }, + { + key: 'company', + type: 'short', + text: 'Company', + extraSettings: { textContains: 'GmbH', textNotContains: 'spam' }, + hint: 'Include “GmbH” · Do not include “spam”', + invalid: 'Spam GmbH', + error: 'Do not include “spam”', + valid: 'ACME gmbh', + }, + { + key: 'reference', + type: 'short', + text: 'Reference', + extraSettings: { textContains: 'REF-' }, + hint: 'Include “REF-”', + invalid: 'ACME 42', + error: 'Include “REF-”', + valid: 'ref-42', + }, + { + key: 'website', + type: 'short', + text: 'Website', + extraSettings: { validationType: 'url' }, + hint: null, + invalid: 'nextcloud.com', + error: 'The input is not a valid URL', + valid: 'https://nextcloud.com', + }, + { + key: 'bio', + type: 'long', + text: 'Bio', + extraSettings: { lengthMin: 5, lengthMax: 40 }, + hint: 'Enter between 5 and 40 characters', + invalid: 'Hi', + error: 'Enter between 5 and 40 characters', + valid: 'Hello there', + }, +] as const + +/** + * Create a form with one question per answer rule + * + * @param request the request context of the page + */ +async function createLimitedForm(request: APIRequestContext) { + const form = await api(request, 'POST', '/forms') + const ids: Record = {} + for (const { key, type, text, extraSettings } of QUESTIONS) { + const created = await api(request, 'POST', `/forms/${form.id}/questions`, { + type, + text, + }) + await api(request, 'PATCH', `/forms/${form.id}/questions/${created.id}`, { + keyValuePairs: { extraSettings }, + }) + ids[key] = created.id + } + return { form, ids } +} + +/** + * Get the answer field of a question in the submit view + * + * @param page the page showing the form + * @param text the title of the question + */ +function answerField(page: Page, text: string) { + return page + .getByRole('listitem') + .filter({ has: page.getByRole('heading', { name: text, exact: true }) }) + .locator('input, textarea') + .first() +} + +/** + * Check that a respondent sees every rule, cannot submit answers breaking + * them and can submit answers keeping them + * + * @param page the page showing the form + */ +async function checkRespondent(page: Page) { + for (const { text, hint } of QUESTIONS) { + if (hint) { + await expect(answerField(page, text)).toHaveAccessibleDescription(hint) + } + } + + const nickname = answerField(page, 'Nickname') + await nickname.fill('abcdefghijklmnopqrstuvwxyz') + await expect(nickname).toHaveValue('abcdefghijkl') + await expect(page.getByText('12 / 12')).toBeVisible() + await answerField(page, 'Bio').fill('Hello') + await expect(page.getByText('5 / 40')).toBeVisible() + + for (const { text, valid } of QUESTIONS) { + await answerField(page, text).fill(valid) + } + for (const { text, invalid, error, valid } of QUESTIONS) { + await answerField(page, text).fill(invalid) + await page.getByRole('button', { name: 'Submit' }).click() + await expect( + page + .getByRole('listitem') + .filter({ + has: page.getByRole('heading', { name: text, exact: true }), + }) + .locator('.notecard--error'), + ).toHaveText(error) + await expect( + page.getByText('Thank you for completing the form!'), + ).toBeHidden() + await answerField(page, text).fill(valid) + } + const submitted = page.waitForResponse( + (response) => + response.request().method() === 'POST' + && response.url().includes('/submissions'), + ) + await page.getByRole('button', { name: 'Submit' }).click() + expect((await submitted).ok()).toBeTruthy() + await expect(page.getByText('Thank you for completing the form!')).toBeVisible() +} + +test.describe('Answer limits', () => { + test('The owner limits the length of a long answer', async ({ + page, + appNavigation, + form, + }) => { + await page.goto('apps/forms') + await page.waitForURL(/apps\/forms\/?$/) + await appNavigation.clickNewForm() + await form.fillTitle('Limits form') + await form.addQuestion(QuestionType.LongAnswer) + const [question] = await form.getQuestions() + await question.fillTitle('Bio') + + await question.openActionsMenu() + const saved = waitForApiResponse(page, 'PATCH') + await page + .getByRole('checkbox', { name: 'Limit the maximum length' }) + .click({ force: true }) + await saved + const updated = waitForApiResponse(page, 'PATCH') + await page.getByRole('spinbutton', { name: 'Maximum characters' }).fill('40') + await updated + + const formId = page.url().match(/apps\/forms\/(\w+)/)![1] + const forms = await api(page.request, 'GET', '/forms') + const { id } = forms.find((f: { hash: string }) => f.hash === formId) + const { questions } = await api(page.request, 'GET', `/forms/${id}`) + expect(questions[0].extraSettings.lengthMax).toBe(40) + }) + + test('The owner sets each rule in the input type menu', async ({ page }) => { + const form = await api(page.request, 'POST', '/forms') + const create = async (text: string, extraSettings: object) => { + const created = await api( + page.request, + 'POST', + `/forms/${form.id}/questions`, + { type: 'short', text }, + ) + await api( + page.request, + 'PATCH', + `/forms/${form.id}/questions/${created.id}`, + { keyValuePairs: { extraSettings } }, + ) + } + await create('Amount', { validationType: 'number' }) + await create('Company', {}) + await create('Website', {}) + const settings = async (index: number) => + (await api(page.request, 'GET', `/forms/${form.id}`)).questions[index] + .extraSettings + const saving = (action: () => Promise) => + Promise.all([waitForApiResponse(page, 'PATCH'), action()]) + + await page.goto(`apps/forms/${form.hash}/edit`) + const items = page.getByRole('listitem', { name: /Question number \d+/ }) + const menu = (index: number, type: string) => + items + .nth(index) + .getByRole('button', { + name: `Input types (currently: ${type})`, + }) + .click() + + await menu(0, 'Number') + await saving(() => + page + .getByRole('radio', { name: 'Not between', exact: true }) + .dispatchEvent('click'), + ) + await saving(() => + page.getByRole('spinbutton', { name: 'Lowest number' }).fill('1'), + ) + await saving(() => + page.getByRole('spinbutton', { name: 'Highest number' }).fill('10'), + ) + expect(await settings(0)).toMatchObject({ + numberMin: 1, + numberMax: 10, + numberExclude: true, + }) + await saving(() => + page + .getByRole('radio', { name: 'Equal to', exact: true }) + .dispatchEvent('click'), + ) + await saving(() => + page.getByRole('spinbutton', { name: 'Number', exact: true }).fill('7'), + ) + expect(await settings(0)).toEqual({ + validationType: 'number', + numberMin: 7, + numberMax: 7, + }) + await saving(() => + page + .getByRole('radio', { name: 'Not equal to', exact: true }) + .dispatchEvent('click'), + ) + expect(await settings(0)).toMatchObject({ numberExclude: true }) + await saving(() => + page + .getByRole('radio', { name: 'Greater than', exact: true }) + .dispatchEvent('click'), + ) + await saving(() => + page.getByRole('spinbutton', { name: 'Number', exact: true }).fill('0'), + ) + expect(await settings(0)).toEqual({ + validationType: 'number', + numberMax: 0, + numberExclude: true, + }) + await saving(() => + page + .getByRole('radio', { name: 'Less than', exact: true }) + .dispatchEvent('click'), + ) + await saving(() => + page + .getByRole('spinbutton', { name: 'Number', exact: true }) + .fill('100'), + ) + expect(await settings(0)).toEqual({ + validationType: 'number', + numberMin: 100, + numberExclude: true, + }) + await saving(() => + page + .getByRole('radio', { name: 'At least', exact: true }) + .dispatchEvent('click'), + ) + await saving(() => + page.getByRole('spinbutton', { name: 'Number', exact: true }).fill('18'), + ) + expect(await settings(0)).toEqual({ + validationType: 'number', + numberMin: 18, + }) + await saving(() => + page + .getByRole('radio', { name: 'At most', exact: true }) + .dispatchEvent('click'), + ) + await saving(() => + page.getByRole('spinbutton', { name: 'Number', exact: true }).fill('50'), + ) + expect(await settings(0)).toEqual({ + validationType: 'number', + numberMax: 50, + }) + await saving(() => + page + .getByRole('radio', { name: 'Between', exact: true }) + .dispatchEvent('click'), + ) + expect(await settings(0)).toEqual({ + validationType: 'number', + numberMin: 0, + numberMax: 50, + }) + await saving(() => + page.getByRole('spinbutton', { name: 'Lowest number' }).fill('1'), + ) + expect(await settings(0)).toEqual({ + validationType: 'number', + numberMin: 1, + numberMax: 50, + }) + await saving(() => + page + .getByRole('checkbox', { name: 'Whole numbers only' }) + .dispatchEvent('click'), + ) + expect(await settings(0)).toMatchObject({ numberInteger: true }) + await page.keyboard.press('Escape') + + await menu(1, 'Text') + await saving(() => + page.getByRole('textbox', { name: 'Must contain' }).fill('GmbH'), + ) + await saving(() => + page.getByRole('textbox', { name: 'Must not contain' }).fill('spam'), + ) + expect(await settings(1)).toEqual({ + textContains: 'GmbH', + textNotContains: 'spam', + }) + await saving(() => + page + .getByRole('checkbox', { name: 'Require a minimum length' }) + .dispatchEvent('click'), + ) + await saving(() => + page.getByRole('spinbutton', { name: 'Minimum characters' }).fill('3'), + ) + await saving(() => + page + .getByRole('checkbox', { name: 'Limit the maximum length' }) + .dispatchEvent('click'), + ) + await saving(() => + page.getByRole('spinbutton', { name: 'Maximum characters' }).fill('12'), + ) + expect(await settings(1)).toMatchObject({ lengthMin: 3, lengthMax: 12 }) + await page.keyboard.press('Escape') + + await menu(2, 'Text') + await saving(() => + page + .getByRole('radio', { name: 'URL', exact: true }) + .dispatchEvent('click'), + ) + expect(await settings(2)).toEqual({ validationType: 'url' }) + }) + + test('A respondent in the app sees the rules and cannot break them', async ({ + page, + }) => { + const { form } = await createLimitedForm(page.request) + await page.goto(`apps/forms/${form.hash}/submit`) + await checkRespondent(page) + }) + + for (const [name, path] of [ + ['a public link', 's'], + ['an embedded form', 'embed'], + ]) { + test(`A respondent of ${name} sees the rules and cannot break them`, async ({ + page, + browser, + baseURL, + }) => { + const { form } = await createLimitedForm(page.request) + const share = await api( + page.request, + 'POST', + `/forms/${form.id}/shares`, + { + shareType: 3, + permissions: ['submit', 'embed'], + }, + ) + const anonymous = await browser.newPage({ + storageState: undefined, + baseURL, + }) + await anonymous.goto(`apps/forms/${path}/${share.shareWith}`) + await checkRespondent(anonymous) + await anonymous.close() + }) + } + + test('The server rejects answers breaking a rule', async ({ + page, + browser, + baseURL, + }) => { + const { form, ids } = await createLimitedForm(page.request) + const share = await api(page.request, 'POST', `/forms/${form.id}/shares`, { + shareType: 3, + }) + const anonymous = await browser.newPage({ storageState: undefined, baseURL }) + const submit = (answers: Record) => + anonymous.request.post( + `../ocs/v2.php/apps/forms/api/v3/forms/${form.id}/submissions`, + { + data: { answers, shareHash: share.shareWith }, + headers: OCS_HEADERS, + }, + ) + const illegal: [string, string][] = [ + ['nickname', 'ab'], + ['nickname', 'abcdefghijklm'], + ['rating', '0.99'], + ['rating', '10.01'], + ['adults', '17.99'], + ['discount', '50.01'], + ['outside', '1'], + ['outside', '10'], + ['lucky', '7.5'], + ['unlucky', '13.0'], + ['price', '0'], + ['price', '-1'], + ['temperature', '100'], + ['temperature', '1e3'], + ['guests', '2.5'], + ['guests', '11'], + ['company', 'ACME'], + ['company', 'GmbH SPAM'], + ['reference', 'RE-42'], + ['website', 'nextcloud.com'], + ['website', 'ftp://nextcloud.com'], + ['website', 'javascript://alert(1)'], + ['bio', 'Hi'], + ['bio', 'x'.repeat(41)], + ] + for (const [key, answer] of illegal) { + const response = await submit({ [ids[key]]: [answer] }) + expect(response.status(), `${key}: ${answer}`).toBe(400) + } + + const valid = Object.fromEntries( + QUESTIONS.map(({ key, valid }) => [ids[key], [valid]]), + ) + expect((await submit(valid)).ok()).toBeTruthy() + await anonymous.close() + }) + + test('The server rejects rules that do not fit together', async ({ page }) => { + const form = await api(page.request, 'POST', '/forms') + const short = await api( + page.request, + 'POST', + `/forms/${form.id}/questions`, + { + type: 'short', + text: 'Short', + }, + ) + const long = await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type: 'long', + text: 'Long', + }) + const patch = (id: number, extraSettings: object) => + page.request.patch( + `../ocs/v2.php/apps/forms/api/v3/forms/${form.id}/questions/${id}`, + { data: { keyValuePairs: { extraSettings } }, headers: OCS_HEADERS }, + ) + const illegal: [number, object][] = [ + [short.id, { validationType: 'number', numberExclude: true }], + [short.id, { validationType: 'number', numberInteger: false }], + [short.id, { numberInteger: true }], + [ + short.id, + { + validationType: 'number', + numberMin: 1, + numberMax: 2, + numberExclude: false, + }, + ], + [short.id, { numberMin: 1, numberMax: 2, numberExclude: true }], + [short.id, { validationType: 'url', textContains: 'nextcloud' }], + [short.id, { textContains: '' }], + [short.id, { textNotContains: 'x'.repeat(4097) }], + [short.id, { validationType: 'url', lengthMax: 20 }], + [short.id, { validationType: 'ftp' }], + [long.id, { textContains: 'Nextcloud' }], + [long.id, { validationType: 'url' }], + ] + for (const [id, extraSettings] of illegal) { + const response = await patch(id, extraSettings) + expect(response.status(), JSON.stringify(extraSettings)).toBe(400) + } + }) +}) diff --git a/src/components/Questions/QuestionLong.vue b/src/components/Questions/QuestionLong.vue index 91bebca17..0623bf96c 100644 --- a/src/components/Questions/QuestionLong.vue +++ b/src/components/Questions/QuestionLong.vue @@ -10,14 +10,54 @@ :titlePlaceholder="answerType.titlePlaceholder" :warningInvalid="answerType.warningInvalid" :errorMessage="errorMessage" + :infoMessage="hasError ? undefined : (limitHint ?? undefined)" v-on="commonListeners"> +