Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions docs/AnswerRules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<!--
- SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->

# 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.
12 changes: 10 additions & 2 deletions docs/DataStructure.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,16 +243,24 @@ 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 |
| ----------------------- | ---------------------------------------------- | ---------------- | ------------------------------------------- | --------------------------------------------------------------------------- |
| `allowOtherAnswer` | `multiple, multiple_unique` | Boolean | `true/false` | Allows the user to specify a custom answer |
| `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 |
Expand Down
16 changes: 15 additions & 1 deletion lib/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,8 @@ class Constants {
'phone',
'email',
'regex',
'number'
'number',
'url',
];

// This are allowed extra settings
Expand All @@ -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'],
Expand Down
8 changes: 8 additions & 0 deletions lib/ResponseDefinitions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -37,6 +43,8 @@
* optionsLowest?: 0|1,
* ratingIcon?: "star"|"heart"|"thumb",
* shuffleOptions?: bool,
* textContains?: string,
* textNotContains?: string,
* timeMax?: string,
* timeMin?: string,
* timeRange?: bool,
Expand Down
72 changes: 72 additions & 0 deletions lib/Service/FormsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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'];
Expand Down Expand Up @@ -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
*
Expand Down
53 changes: 53 additions & 0 deletions lib/Service/SubmissionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down
Loading
Loading